Browse Source

Merge pull request #1567 from SixLabors/icc-color-conversion

Color conversion with ICC profiles
pull/2926/head
James Jackson-South 1 year ago
committed by GitHub
parent
commit
ba61e04e4b
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 12
      .editorconfig
  2. 7
      .gitattributes
  3. 2
      shared-infrastructure
  4. 46
      src/ImageSharp/ColorProfiles/CieLab.cs
  5. 56
      src/ImageSharp/ColorProfiles/CieLch.cs
  6. 56
      src/ImageSharp/ColorProfiles/CieLchuv.cs
  7. 15
      src/ImageSharp/ColorProfiles/CieLuv.cs
  8. 33
      src/ImageSharp/ColorProfiles/CieXyy.cs
  9. 86
      src/ImageSharp/ColorProfiles/CieXyz.cs
  10. 49
      src/ImageSharp/ColorProfiles/Cmyk.cs
  11. 39
      src/ImageSharp/ColorProfiles/ColorConversionOptions.cs
  12. 9
      src/ImageSharp/ColorProfiles/ColorProfileConverter.cs
  13. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabCieLab.cs
  14. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabCieXyz.cs
  15. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabRgb.cs
  16. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzCieLab.cs
  17. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzCieXyz.cs
  18. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzRgb.cs
  19. 731
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsIcc.cs
  20. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbCieLab.cs
  21. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbCieXyz.cs
  22. 11
      src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbRgb.cs
  23. 42
      src/ImageSharp/ColorProfiles/Hsl.cs
  24. 42
      src/ImageSharp/ColorProfiles/Hsv.cs
  25. 45
      src/ImageSharp/ColorProfiles/HunterLab.cs
  26. 48
      src/ImageSharp/ColorProfiles/IColorProfile.cs
  27. 506
      src/ImageSharp/ColorProfiles/Icc/Calculators/ClutCalculator.cs
  28. 65
      src/ImageSharp/ColorProfiles/Icc/Calculators/ColorTrcCalculator.cs
  29. 14
      src/ImageSharp/ColorProfiles/Icc/Calculators/CurveCalculator.CalculationType.cs
  30. 47
      src/ImageSharp/ColorProfiles/Icc/Calculators/CurveCalculator.cs
  31. 19
      src/ImageSharp/ColorProfiles/Icc/Calculators/GrayTrcCalculator.cs
  32. 17
      src/ImageSharp/ColorProfiles/Icc/Calculators/ISingleCalculator.cs
  33. 19
      src/ImageSharp/ColorProfiles/Icc/Calculators/IVector4Calculator.cs
  34. 18
      src/ImageSharp/ColorProfiles/Icc/Calculators/LutABCalculator.CalculationType.cs
  35. 135
      src/ImageSharp/ColorProfiles/Icc/Calculators/LutABCalculator.cs
  36. 77
      src/ImageSharp/ColorProfiles/Icc/Calculators/LutCalculator.cs
  37. 80
      src/ImageSharp/ColorProfiles/Icc/Calculators/LutEntryCalculator.cs
  38. 26
      src/ImageSharp/ColorProfiles/Icc/Calculators/MatrixCalculator.cs
  39. 130
      src/ImageSharp/ColorProfiles/Icc/Calculators/ParametricCurveCalculator.cs
  40. 41
      src/ImageSharp/ColorProfiles/Icc/Calculators/TrcCalculator.cs
  41. 155
      src/ImageSharp/ColorProfiles/Icc/IccConverterBase.Checks.cs
  42. 66
      src/ImageSharp/ColorProfiles/Icc/IccConverterBase.ConversionMethod.cs
  43. 109
      src/ImageSharp/ColorProfiles/Icc/IccConverterbase.Conversions.cs
  44. 49
      src/ImageSharp/ColorProfiles/Icc/IccConverterbase.cs
  45. 22
      src/ImageSharp/ColorProfiles/Icc/IccDataToDataConverter.cs
  46. 22
      src/ImageSharp/ColorProfiles/Icc/IccDataToPcsConverter.cs
  47. 22
      src/ImageSharp/ColorProfiles/Icc/IccPcsToDataConverter.cs
  48. 22
      src/ImageSharp/ColorProfiles/Icc/IccPcsToPcsConverter.cs
  49. 45
      src/ImageSharp/ColorProfiles/Icc/SrgbV4Profile.Generated.cs
  50. 62
      src/ImageSharp/ColorProfiles/KnownYCbCrMatrices.cs
  51. 56
      src/ImageSharp/ColorProfiles/Lms.cs
  52. 104
      src/ImageSharp/ColorProfiles/Rgb.cs
  53. 12
      src/ImageSharp/ColorProfiles/VonKriesChromaticAdaptation.cs
  54. 142
      src/ImageSharp/ColorProfiles/Y.cs
  55. 86
      src/ImageSharp/ColorProfiles/YCbCr.cs
  56. 61
      src/ImageSharp/ColorProfiles/YcbCrMatrix.cs
  57. 206
      src/ImageSharp/ColorProfiles/YccK.cs
  58. 21
      src/ImageSharp/Common/Extensions/Vector4Extensions.cs
  59. 21
      src/ImageSharp/Formats/ColorProfileHandling.cs
  60. 6
      src/ImageSharp/Formats/DecoderOptions.cs
  61. 8
      src/ImageSharp/Formats/ImageDecoder.cs
  62. 4
      src/ImageSharp/Formats/SpecializedImageDecoder{T}.cs
  63. 85
      src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Lut.cs
  64. 28
      src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Matrix.cs
  65. 35
      src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Primitives.cs
  66. 132
      src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs
  67. 59
      src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.Lut.cs
  68. 31
      src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.Matrix.cs
  69. 2
      src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs
  70. 2
      src/ImageSharp/Metadata/Profiles/ICC/Enums/IccFormulaCurveType.cs
  71. 2
      src/ImageSharp/Metadata/Profiles/ICC/Exceptions/InvalidIccProfileException.cs
  72. 2
      src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs
  73. 21
      src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs
  74. 6
      src/ImageSharp/Metadata/Profiles/ICC/IccTagDataEntry.cs
  75. 100
      src/ImageSharp/Metadata/Profiles/ICC/Various/IccClut.cs
  76. 10
      src/ImageSharp/Metadata/Profiles/ICC/Various/IccTagTableEntry.cs
  77. 3
      src/ImageSharp/PixelFormats/IPixel.cs
  78. 3
      src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs
  79. 2
      src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs
  80. 2
      tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs
  81. 12
      tests/ImageSharp.Tests/ColorProfiles/ApproximateColorProfileComparer.cs
  82. 5
      tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLchConversionTests.cs
  83. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLchuvConversionTests.cs
  84. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLuvConversionTests.cs
  85. 10
      tests/ImageSharp.Tests/ColorProfiles/CieLabAndYCbCrConversionTests.cs
  86. 1
      tests/ImageSharp.Tests/ColorProfiles/CieLabTests.cs
  87. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLchAndCieLuvConversionTests.cs
  88. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCieLchConversionTests.cs
  89. 5
      tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCieLuvConversionTests.cs
  90. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCmykConversionTests.cs
  91. 1
      tests/ImageSharp.Tests/ColorProfiles/CieLchuvTests.cs
  92. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndCieXyyConversionTests.cs
  93. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHslConversionTests.cs
  94. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHsvConversionTests.cs
  95. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHunterLabConversionTests.cs
  96. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndLmsConversionTests.cs
  97. 4
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndRgbConversionTests.cs
  98. 14
      tests/ImageSharp.Tests/ColorProfiles/CieLuvAndYCbCrConversionTests.cs
  99. 1
      tests/ImageSharp.Tests/ColorProfiles/CieLuvTests.cs
  100. 1
      tests/ImageSharp.Tests/ColorProfiles/CieXyChromaticityCoordinatesTests.cs

12
.editorconfig

@ -104,8 +104,8 @@ dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:war
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_other_operators = always_for_clarity:suggestion
# Expression-level preferences
dotnet_style_object_initializer = true:warning
dotnet_style_collection_initializer = true:warning
dotnet_style_object_initializer = true:error
dotnet_style_collection_initializer = true:error
dotnet_style_explicit_tuple_names = true:warning
dotnet_style_prefer_inferred_tuple_names = true:warning
dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
@ -135,9 +135,9 @@ csharp_style_prefer_null_check_over_type_check = true:warning
# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules
[*.{cs,csx,cake}]
# 'var' preferences
csharp_style_var_for_built_in_types = false:warning
csharp_style_var_when_type_is_apparent = false:warning
csharp_style_var_elsewhere = false:warning
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
csharp_style_var_elsewhere = false:error
# Expression-bodied members
csharp_style_expression_bodied_methods = true:warning
csharp_style_expression_bodied_constructors = true:warning
@ -160,7 +160,7 @@ csharp_style_pattern_local_over_anonymous_function = true:warning
csharp_style_deconstructed_variable_declaration = true:warning
csharp_style_prefer_index_operator = true:warning
csharp_style_prefer_range_operator = true:warning
csharp_style_implicit_object_creation_when_type_is_apparent = true:warning
csharp_style_implicit_object_creation_when_type_is_apparent = true:error
# "Null" checking preferences
csharp_style_throw_expression = true:warning
csharp_style_conditional_delegate_call = true:warning

7
.gitattributes

@ -136,3 +136,10 @@
*.ico filter=lfs diff=lfs merge=lfs -text
*.cur filter=lfs diff=lfs merge=lfs -text
*.ani filter=lfs diff=lfs merge=lfs -text
*.heic filter=lfs diff=lfs merge=lfs -text
*.hif filter=lfs diff=lfs merge=lfs -text
*.avif filter=lfs diff=lfs merge=lfs -text
###############################################################################
# Handle ICC files by git lfs
###############################################################################
*.icc filter=lfs diff=lfs merge=lfs -text

2
shared-infrastructure

@ -1 +1 @@
Subproject commit 1dbfb576c83507645265c79e03369b66cdc0379f
Subproject commit 5e13cde851a3d6e95d0dfdde2a57071f1efda9c3

46
src/ImageSharp/ColorProfiles/CieLab.cs

@ -35,7 +35,6 @@ public readonly struct CieLab : IProfileConnectingSpace<CieLab, CieXyz>
/// <param name="vector">The vector representing the l, a, b components.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CieLab(Vector3 vector)
: this()
{
this.L = vector.X;
this.A = vector.Y;
@ -82,6 +81,49 @@ public readonly struct CieLab : IProfileConnectingSpace<CieLab, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(CieLab left, CieLab right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 += new Vector3(0, 128F, 128F);
v3 /= new Vector3(100F, 255F, 255F);
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public static CieLab FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= new Vector3(100F, 255, 255);
v3 -= new Vector3(0, 128F, 128F);
return new CieLab(v3);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieLab> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieLab> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static CieLab FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
@ -136,7 +178,7 @@ public readonly struct CieLab : IProfileConnectingSpace<CieLab, CieXyz>
float yr = l > CieConstants.Kappa * CieConstants.Epsilon ? Numerics.Pow3((l + 16F) / 116F) : l / CieConstants.Kappa;
float zr = fz3 > CieConstants.Epsilon ? fz3 : ((116F * fz) - 16F) / CieConstants.Kappa;
CieXyz whitePoint = options.WhitePoint;
CieXyz whitePoint = options.SourceWhitePoint;
Vector3 wxyz = new(whitePoint.X, whitePoint.Y, whitePoint.Z);
Vector3 xyzr = new(xr, yr, zr);

56
src/ImageSharp/ColorProfiles/CieLch.cs

@ -42,6 +42,17 @@ public readonly struct CieLch : IColorProfile<CieLch, CieLab>
this.H = vector.Z;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private CieLch(Vector3 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
vector = Vector3.Clamp(vector, Min, Max);
this.L = vector.X;
this.C = vector.Y;
this.H = vector.Z;
}
/// <summary>
/// Gets the lightness dimension.
/// <remarks>A value ranging between 0 (black), 100 (diffuse white) or higher (specular white).</remarks>
@ -50,7 +61,7 @@ public readonly struct CieLch : IColorProfile<CieLch, CieLab>
/// <summary>
/// Gets the a chroma component.
/// <remarks>A value ranging from 0 to 200.</remarks>
/// <remarks>A value ranging from -200 to 200.</remarks>
/// </summary>
public float C { get; }
@ -82,6 +93,49 @@ public readonly struct CieLch : IColorProfile<CieLch, CieLab>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(CieLch left, CieLch right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 += new Vector3(0, 200, 0);
v3 /= new Vector3(100, 400, 360);
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public static CieLch FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= new Vector3(100, 400, 360);
v3 -= new Vector3(0, 200, 0);
return new CieLch(v3, true);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieLch> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieLch> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static CieLch FromProfileConnectingSpace(ColorConversionOptions options, in CieLab source)
{

56
src/ImageSharp/ColorProfiles/CieLchuv.cs

@ -35,7 +35,6 @@ public readonly struct CieLchuv : IColorProfile<CieLchuv, CieXyz>
/// <param name="vector">The vector representing the l, c, h components.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CieLchuv(Vector3 vector)
: this()
{
vector = Vector3.Clamp(vector, Min, Max);
this.L = vector.X;
@ -43,6 +42,16 @@ public readonly struct CieLchuv : IColorProfile<CieLchuv, CieXyz>
this.H = vector.Z;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private CieLchuv(Vector3 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.L = vector.X;
this.C = vector.Y;
this.H = vector.Z;
}
/// <summary>
/// Gets the lightness dimension.
/// <remarks>A value ranging between 0 (black), 100 (diffuse white) or higher (specular white).</remarks>
@ -51,7 +60,7 @@ public readonly struct CieLchuv : IColorProfile<CieLchuv, CieXyz>
/// <summary>
/// Gets the a chroma component.
/// <remarks>A value ranging from 0 to 200.</remarks>
/// <remarks>A value ranging from -200 to 200.</remarks>
/// </summary>
public float C { get; }
@ -81,6 +90,49 @@ public readonly struct CieLchuv : IColorProfile<CieLchuv, CieXyz>
/// </returns>
public static bool operator !=(CieLchuv left, CieLchuv right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 += new Vector3(0, 200, 0);
v3 /= new Vector3(100, 400, 360);
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public static CieLchuv FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= new Vector3(100, 400, 360);
v3 -= new Vector3(0, 200, 0);
return new CieLchuv(v3, true);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieLchuv> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieLchuv> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static CieLchuv FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
{

15
src/ImageSharp/ColorProfiles/CieLuv.cs

@ -37,7 +37,6 @@ public readonly struct CieLuv : IColorProfile<CieLuv, CieXyz>
/// <param name="vector">The vector representing the l, u, v components.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CieLuv(Vector3 vector)
: this()
{
this.L = vector.X;
this.U = vector.Y;
@ -84,6 +83,18 @@ public readonly struct CieLuv : IColorProfile<CieLuv, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(CieLuv left, CieLuv right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4() => throw new NotImplementedException();
/// <inheritdoc/>
public static CieLuv FromScaledVector4(Vector4 source) => throw new NotImplementedException();
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieLuv> source, Span<Vector4> destination) => throw new NotImplementedException();
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieLuv> destination) => throw new NotImplementedException();
/// <inheritdoc/>
public static CieLuv FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
{
@ -143,7 +154,7 @@ public readonly struct CieLuv : IColorProfile<CieLuv, CieXyz>
// Use doubles here for accuracy.
// Conversion algorithm described here:
// http://www.brucelindbloom.com/index.html?Eqn_Luv_to_XYZ.html
CieXyz whitePoint = options.WhitePoint;
CieXyz whitePoint = options.SourceWhitePoint;
double l = this.L, u = this.U, v = this.V;

33
src/ImageSharp/ColorProfiles/CieXyy.cs

@ -35,7 +35,6 @@ public readonly struct CieXyy : IColorProfile<CieXyy, CieXyz>
/// <param name="vector">The vector representing the x, y, Y components.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CieXyy(Vector3 vector)
: this()
{
// Not clamping as documentation about this space only indicates "usual" ranges
this.X = vector.X;
@ -83,6 +82,38 @@ public readonly struct CieXyy : IColorProfile<CieXyy, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(CieXyy left, CieXyy right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
=> new(this.AsVector3Unsafe(), 1F);
/// <inheritdoc/>
public static CieXyy FromScaledVector4(Vector4 source)
=> new(source.AsVector3());
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieXyy> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieXyy> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static CieXyy FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
{

86
src/ImageSharp/ColorProfiles/CieXyz.cs

@ -34,7 +34,6 @@ public readonly struct CieXyz : IProfileConnectingSpace<CieXyz, CieXyz>
/// </summary>
/// <param name="vector">The vector representing the x, y, z components.</param>
public CieXyz(Vector3 vector)
: this()
{
this.X = vector.X;
this.Y = vector.Y;
@ -81,12 +80,85 @@ public readonly struct CieXyz : IProfileConnectingSpace<CieXyz, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(CieXyz left, CieXyz right) => !left.Equals(right);
/// <summary>
/// Returns a new <see cref="Vector3"/> representing this instance.
/// </summary>
/// <returns>The <see cref="Vector3"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 ToVector3() => new(this.X, this.Y, this.Z);
internal Vector3 ToVector3() => new(this.X, this.Y, this.Z);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Vector4 ToVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 *= 32768F / 65535;
return new Vector4(v3, 1F);
}
internal static CieXyz FromVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
return new CieXyz(v3);
}
/// <inheritdoc/>
public static CieXyz FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= 65535 / 32768F;
return new CieXyz(v3);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<CieXyz> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<CieXyz> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
internal static void FromVector4(ReadOnlySpan<Vector4> source, Span<CieXyz> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromVector4(source[i]);
}
}
internal static void ToVector4(ReadOnlySpan<CieXyz> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToVector4();
}
}
/// <inheritdoc/>
public static CieXyz FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
@ -127,5 +199,5 @@ public readonly struct CieXyz : IProfileConnectingSpace<CieXyz, CieXyz>
public bool Equals(CieXyz other)
=> this.AsVector3Unsafe() == other.AsVector3Unsafe();
private Vector3 AsVector3Unsafe() => Unsafe.As<CieXyz, Vector3>(ref Unsafe.AsRef(in this));
internal Vector3 AsVector3Unsafe() => Unsafe.As<CieXyz, Vector3>(ref Unsafe.AsRef(in this));
}

49
src/ImageSharp/ColorProfiles/Cmyk.cs

@ -9,6 +9,7 @@ namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// Represents an CMYK (cyan, magenta, yellow, keyline) color.
/// <see href="https://en.wikipedia.org/wiki/CMYK_color_model"/>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct Cmyk : IColorProfile<Cmyk, Rgb>
@ -36,7 +37,18 @@ public readonly struct Cmyk : IColorProfile<Cmyk, Rgb>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Cmyk(Vector4 vector)
{
vector = Numerics.Clamp(vector, Min, Max);
vector = Vector4.Clamp(vector, Min, Max);
this.C = vector.X;
this.M = vector.Y;
this.Y = vector.Z;
this.K = vector.W;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private Cmyk(Vector4 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.C = vector.X;
this.M = vector.Y;
this.Y = vector.Z;
@ -89,16 +101,42 @@ public readonly struct Cmyk : IColorProfile<Cmyk, Rgb>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Cmyk left, Cmyk right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector4 v4 = default;
v4 += this.AsVector4Unsafe();
return v4;
}
/// <inheritdoc/>
public static Cmyk FromScaledVector4(Vector4 source)
=> new(source, true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Cmyk> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
MemoryMarshal.Cast<Cmyk, Vector4>(source).CopyTo(destination);
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Cmyk> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
MemoryMarshal.Cast<Vector4, Cmyk>(source).CopyTo(destination);
}
/// <inheritdoc/>
public static Cmyk FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{
// To CMY
Vector3 cmy = Vector3.One - source.ToScaledVector3();
Vector3 cmy = Vector3.One - source.AsVector3Unsafe();
// To CMYK
Vector3 k = new(MathF.Min(cmy.X, MathF.Min(cmy.Y, cmy.Z)));
if (MathF.Abs(k.X - 1F) < Constants.Epsilon)
if (k.X >= 1F - Constants.Epsilon)
{
return new Cmyk(0, 0, 0, 1F);
}
@ -124,7 +162,7 @@ public readonly struct Cmyk : IColorProfile<Cmyk, Rgb>
/// <inheritdoc/>
public Rgb ToProfileConnectingSpace(ColorConversionOptions options)
{
Vector3 rgb = (Vector3.One - new Vector3(this.C, this.M, this.Y)) * (Vector3.One - new Vector3(this.K));
Vector3 rgb = (Vector3.One - new Vector3(this.C, this.M, this.Y)) * (1F - this.K);
return Rgb.FromScaledVector3(rgb);
}
@ -134,8 +172,7 @@ public readonly struct Cmyk : IColorProfile<Cmyk, Rgb>
// TODO: We can possibly optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
Cmyk cmyk = source[i];
destination[i] = cmyk.ToProfileConnectingSpace(options);
destination[i] = source[i].ToProfileConnectingSpace(options);
}
}

39
src/ImageSharp/ColorProfiles/ColorConversionOptions.cs

@ -4,6 +4,7 @@
using System.Numerics;
using SixLabors.ImageSharp.ColorProfiles.WorkingSpaces;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles;
@ -13,11 +14,16 @@ namespace SixLabors.ImageSharp.ColorProfiles;
public class ColorConversionOptions
{
private Matrix4x4 adaptationMatrix;
private YCbCrMatrix yCbCrMatrix;
/// <summary>
/// Initializes a new instance of the <see cref="ColorConversionOptions"/> class.
/// </summary>
public ColorConversionOptions() => this.AdaptationMatrix = KnownChromaticAdaptationMatrices.Bradford;
public ColorConversionOptions()
{
this.AdaptationMatrix = KnownChromaticAdaptationMatrices.Bradford;
this.YCbCrMatrix = KnownYCbCrMatrices.BT601;
}
/// <summary>
/// Gets the memory allocator.
@ -27,7 +33,7 @@ public class ColorConversionOptions
/// <summary>
/// Gets the source white point used for chromatic adaptation in conversions from/to XYZ color space.
/// </summary>
public CieXyz WhitePoint { get; init; } = KnownIlluminants.D50;
public CieXyz SourceWhitePoint { get; init; } = KnownIlluminants.D50;
/// <summary>
/// Gets the destination white point used for chromatic adaptation in conversions from/to XYZ color space.
@ -37,13 +43,36 @@ public class ColorConversionOptions
/// <summary>
/// Gets the source working space used for companding in conversions from/to XYZ color space.
/// </summary>
public RgbWorkingSpace RgbWorkingSpace { get; init; } = KnownRgbWorkingSpaces.SRgb;
public RgbWorkingSpace SourceRgbWorkingSpace { get; init; } = KnownRgbWorkingSpaces.SRgb;
/// <summary>
/// Gets the destination working space used for companding in conversions from/to XYZ color space.
/// </summary>
public RgbWorkingSpace TargetRgbWorkingSpace { get; init; } = KnownRgbWorkingSpaces.SRgb;
/// <summary>
/// Gets the YCbCr matrix to used to perform conversions from/to RGB.
/// </summary>
public YCbCrMatrix YCbCrMatrix
{
get => this.yCbCrMatrix;
init
{
this.yCbCrMatrix = value;
this.TransposedYCbCrMatrix = value.Transpose();
}
}
/// <summary>
/// Gets the source ICC profile.
/// </summary>
public IccProfile? SourceIccProfile { get; init; }
/// <summary>
/// Gets the target ICC profile.
/// </summary>
public IccProfile? TargetIccProfile { get; init; }
/// <summary>
/// Gets the transformation matrix used in conversion to perform chromatic adaptation.
/// <see cref="KnownChromaticAdaptationMatrices"/> for further information. Default is Bradford.
@ -54,10 +83,12 @@ public class ColorConversionOptions
init
{
this.adaptationMatrix = value;
Matrix4x4.Invert(value, out Matrix4x4 inverted);
_ = Matrix4x4.Invert(value, out Matrix4x4 inverted);
this.InverseAdaptationMatrix = inverted;
}
}
internal YCbCrMatrix TransposedYCbCrMatrix { get; private set; }
internal Matrix4x4 InverseAdaptationMatrix { get; private set; }
}

9
src/ImageSharp/ColorProfiles/ColorProfileConverter.cs

@ -12,7 +12,7 @@ public class ColorProfileConverter
/// Initializes a new instance of the <see cref="ColorProfileConverter"/> class.
/// </summary>
public ColorProfileConverter()
: this(new())
: this(new())
{
}
@ -33,8 +33,8 @@ public class ColorProfileConverter
where TTo : struct, IColorProfile
{
CieXyz sourceWhitePoint = TFrom.GetChromaticAdaptionWhitePointSource() == ChromaticAdaptionWhitePointSource.WhitePoint
? this.Options.WhitePoint
: this.Options.RgbWorkingSpace.WhitePoint;
? this.Options.SourceWhitePoint
: this.Options.SourceRgbWorkingSpace.WhitePoint;
CieXyz targetWhitePoint = TTo.GetChromaticAdaptionWhitePointSource() == ChromaticAdaptionWhitePointSource.WhitePoint
? this.Options.TargetWhitePoint
@ -42,4 +42,7 @@ public class ColorProfileConverter
return (sourceWhitePoint, targetWhitePoint);
}
internal bool ShouldUseIccProfiles()
=> this.Options.SourceIccProfile != null && this.Options.TargetIccProfile != null;
}

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabCieLab.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieLabCieLab
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -33,6 +38,12 @@ internal static class ColorProfileConverterExtensionsCieLabCieLab
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabCieXyz.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieLabCieXyz
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -32,6 +37,12 @@ internal static class ColorProfileConverterExtensionsCieLabCieXyz
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieLabRgb.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieLabRgb
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -33,6 +38,12 @@ internal static class ColorProfileConverterExtensionsCieLabRgb
where TFrom : struct, IColorProfile<TFrom, CieLab>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzCieLab.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieXyzCieLab
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -32,6 +37,12 @@ internal static class ColorProfileConverterExtensionsCieXyzCieLab
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzCieXyz.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieXyzCieXyz
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -29,6 +34,12 @@ internal static class ColorProfileConverterExtensionsCieXyzCieXyz
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsCieXyzRgb.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsCieXyzRgb
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -32,6 +37,12 @@ internal static class ColorProfileConverterExtensionsCieXyzRgb
where TFrom : struct, IColorProfile<TFrom, CieXyz>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

731
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsIcc.cs

@ -0,0 +1,731 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.ColorProfiles.Icc;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles;
internal static class ColorProfileConverterExtensionsIcc
{
private static readonly float[] PcsV2FromBlackPointScale =
[0.9965153F, 0.9965269F, 0.9965208F, 1F,
0.9965153F, 0.9965269F, 0.9965208F, 1F,
0.9965153F, 0.9965269F, 0.9965208F, 1F,
0.9965153F, 0.9965269F, 0.9965208F, 1F];
private static readonly float[] PcsV2FromBlackPointOffset =
[0.00336F, 0.0034731F, 0.00287F, 0F,
0.00336F, 0.0034731F, 0.00287F, 0F,
0.00336F, 0.0034731F, 0.00287F, 0F,
0.00336F, 0.0034731F, 0.00287F, 0F];
private static readonly float[] PcsV2ToBlackPointScale =
[1.0034969F, 1.0034852F, 1.0034913F, 1F,
1.0034969F, 1.0034852F, 1.0034913F, 1F,
1.0034969F, 1.0034852F, 1.0034913F, 1F,
1.0034969F, 1.0034852F, 1.0034913F, 1F];
private static readonly float[] PcsV2ToBlackPointOffset =
[0.0033717495F, 0.0034852044F, 0.0028800198F, 0F,
0.0033717495F, 0.0034852044F, 0.0028800198F, 0F,
0.0033717495F, 0.0034852044F, 0.0028800198F, 0F,
0.0033717495F, 0.0034852044F, 0.0028800198F, 0F];
internal static TTo ConvertUsingIccProfile<TFrom, TTo>(this ColorProfileConverter converter, in TFrom source)
where TFrom : struct, IColorProfile<TFrom>
where TTo : struct, IColorProfile<TTo>
{
// TODO: Validation of ICC Profiles against color profile. Is this possible?
if (converter.Options.SourceIccProfile is null)
{
throw new InvalidOperationException("Source ICC profile is missing.");
}
if (converter.Options.TargetIccProfile is null)
{
throw new InvalidOperationException("Target ICC profile is missing.");
}
ConversionParams sourceParams = new(converter.Options.SourceIccProfile, toPcs: true);
ConversionParams targetParams = new(converter.Options.TargetIccProfile, toPcs: false);
ColorProfileConverter pcsConverter = new(new ColorConversionOptions
{
MemoryAllocator = converter.Options.MemoryAllocator,
SourceWhitePoint = new CieXyz(converter.Options.SourceIccProfile.Header.PcsIlluminant),
TargetWhitePoint = new CieXyz(converter.Options.TargetIccProfile.Header.PcsIlluminant),
});
// Normalize the source, then convert to the PCS space.
Vector4 sourcePcs = sourceParams.Converter.Calculate(source.ToScaledVector4());
// If both profiles need PCS adjustment, they both share the same unadjusted PCS space
// cancelling out the need to make the adjustment
// except if using TRC transforms, which always requires perceptual handling
// TODO: this does not include adjustment for absolute intent, which would double existing complexity, suggest throwing exception and addressing in future update
bool anyProfileNeedsPerceptualAdjustment = sourceParams.HasNoPerceptualHandling || targetParams.HasNoPerceptualHandling;
bool oneProfileHasV2PerceptualAdjustment = sourceParams.HasV2PerceptualHandling ^ targetParams.HasV2PerceptualHandling;
Vector4 targetPcs = anyProfileNeedsPerceptualAdjustment || oneProfileHasV2PerceptualAdjustment
? GetTargetPcsWithPerceptualAdjustment(sourcePcs, sourceParams, targetParams, pcsConverter)
: GetTargetPcsWithoutAdjustment(sourcePcs, sourceParams, targetParams, pcsConverter);
return TTo.FromScaledVector4(targetParams.Converter.Calculate(targetPcs));
}
internal static void ConvertUsingIccProfile<TFrom, TTo>(this ColorProfileConverter converter, ReadOnlySpan<TFrom> source, Span<TTo> destination)
where TFrom : struct, IColorProfile<TFrom>
where TTo : struct, IColorProfile<TTo>
{
// TODO: Validation of ICC Profiles against color profile. Is this possible?
if (converter.Options.SourceIccProfile is null)
{
throw new InvalidOperationException("Source ICC profile is missing.");
}
if (converter.Options.TargetIccProfile is null)
{
throw new InvalidOperationException("Target ICC profile is missing.");
}
Guard.MustBeGreaterThanOrEqualTo(source.Length, destination.Length, nameof(destination));
ConversionParams sourceParams = new(converter.Options.SourceIccProfile, toPcs: true);
ConversionParams targetParams = new(converter.Options.TargetIccProfile, toPcs: false);
ColorProfileConverter pcsConverter = new(new ColorConversionOptions
{
MemoryAllocator = converter.Options.MemoryAllocator,
SourceWhitePoint = new CieXyz(converter.Options.SourceIccProfile.Header.PcsIlluminant),
TargetWhitePoint = new CieXyz(converter.Options.TargetIccProfile.Header.PcsIlluminant),
});
using IMemoryOwner<Vector4> pcsBuffer = converter.Options.MemoryAllocator.Allocate<Vector4>(source.Length);
Span<Vector4> pcs = pcsBuffer.GetSpan();
// Normalize the source, then convert to the PCS space.
TFrom.ToScaledVector4(source, pcs);
sourceParams.Converter.Calculate(pcs, pcs);
// If both profiles need PCS adjustment, they both share the same unadjusted PCS space
// cancelling out the need to make the adjustment
// except if using TRC transforms, which always requires perceptual handling
// TODO: this does not include adjustment for absolute intent, which would double existing complexity, suggest throwing exception and addressing in future update
bool anyProfileNeedsPerceptualAdjustment = sourceParams.HasNoPerceptualHandling || targetParams.HasNoPerceptualHandling;
bool oneProfileHasV2PerceptualAdjustment = sourceParams.HasV2PerceptualHandling ^ targetParams.HasV2PerceptualHandling;
if (anyProfileNeedsPerceptualAdjustment || oneProfileHasV2PerceptualAdjustment)
{
GetTargetPcsWithPerceptualAdjustment(pcs, sourceParams, targetParams, pcsConverter);
}
else
{
GetTargetPcsWithoutAdjustment(pcs, sourceParams, targetParams, pcsConverter);
}
// Convert to the target space.
targetParams.Converter.Calculate(pcs, pcs);
TTo.FromScaledVector4(pcs, destination);
}
private static Vector4 GetTargetPcsWithoutAdjustment(
Vector4 sourcePcs,
ConversionParams sourceParams,
ConversionParams targetParams,
ColorProfileConverter pcsConverter)
{
// Profile connecting spaces can only be Lab, XYZ.
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so ensure that Lab is using the correct encoding when a 16-bit LUT is used
switch (sourceParams.PcsType)
{
// Convert from Lab to XYZ.
case IccColorSpaceType.CieLab when targetParams.PcsType is IccColorSpaceType.CieXyz:
{
sourcePcs = sourceParams.Is16BitLutEntry ? LabV2ToLab(sourcePcs) : sourcePcs;
CieLab lab = CieLab.FromScaledVector4(sourcePcs);
CieXyz xyz = pcsConverter.Convert<CieLab, CieXyz>(in lab);
return xyz.ToScaledVector4();
}
// Convert from XYZ to Lab.
case IccColorSpaceType.CieXyz when targetParams.PcsType is IccColorSpaceType.CieLab:
{
CieXyz xyz = CieXyz.FromScaledVector4(sourcePcs);
CieLab lab = pcsConverter.Convert<CieXyz, CieLab>(in xyz);
Vector4 targetPcs = lab.ToScaledVector4();
return targetParams.Is16BitLutEntry ? LabToLabV2(targetPcs) : targetPcs;
}
// Convert from XYZ to XYZ.
case IccColorSpaceType.CieXyz when targetParams.PcsType is IccColorSpaceType.CieXyz:
{
CieXyz xyz = CieXyz.FromScaledVector4(sourcePcs);
CieXyz targetXyz = pcsConverter.Convert<CieXyz, CieXyz>(in xyz);
return targetXyz.ToScaledVector4();
}
// Convert from Lab to Lab.
case IccColorSpaceType.CieLab when targetParams.PcsType is IccColorSpaceType.CieLab:
{
// if both source and target LUT use same v2 LAB encoding, no need to correct them
if (sourceParams.Is16BitLutEntry && targetParams.Is16BitLutEntry)
{
CieLab sourceLab = CieLab.FromScaledVector4(sourcePcs);
CieLab targetLab = pcsConverter.Convert<CieLab, CieLab>(in sourceLab);
return targetLab.ToScaledVector4();
}
else
{
sourcePcs = sourceParams.Is16BitLutEntry ? LabV2ToLab(sourcePcs) : sourcePcs;
CieLab sourceLab = CieLab.FromScaledVector4(sourcePcs);
CieLab targetLab = pcsConverter.Convert<CieLab, CieLab>(in sourceLab);
Vector4 targetPcs = targetLab.ToScaledVector4();
return targetParams.Is16BitLutEntry ? LabToLabV2(targetPcs) : targetPcs;
}
}
default:
throw new ArgumentOutOfRangeException($"Source PCS {sourceParams.PcsType} to target PCS {targetParams.PcsType} is not supported");
}
}
private static void GetTargetPcsWithoutAdjustment(
Span<Vector4> pcs,
ConversionParams sourceParams,
ConversionParams targetParams,
ColorProfileConverter pcsConverter)
{
// Profile connecting spaces can only be Lab, XYZ.
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so ensure that Lab is using the correct encoding when a 16-bit LUT is used
switch (sourceParams.PcsType)
{
// Convert from Lab to XYZ.
case IccColorSpaceType.CieLab when targetParams.PcsType is IccColorSpaceType.CieXyz:
{
if (sourceParams.Is16BitLutEntry)
{
LabV2ToLab(pcs, pcs);
}
using IMemoryOwner<CieLab> pcsFromBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieLab>(pcs.Length);
Span<CieLab> pcsFrom = pcsFromBuffer.GetSpan();
using IMemoryOwner<CieXyz> pcsToBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieXyz>(pcs.Length);
Span<CieXyz> pcsTo = pcsToBuffer.GetSpan();
CieLab.FromScaledVector4(pcs, pcsFrom);
pcsConverter.Convert<CieLab, CieXyz>(pcsFrom, pcsTo);
CieXyz.ToScaledVector4(pcsTo, pcs);
break;
}
// Convert from XYZ to Lab.
case IccColorSpaceType.CieXyz when targetParams.PcsType is IccColorSpaceType.CieLab:
{
using IMemoryOwner<CieXyz> pcsFromBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieXyz>(pcs.Length);
Span<CieXyz> pcsFrom = pcsFromBuffer.GetSpan();
using IMemoryOwner<CieLab> pcsToBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieLab>(pcs.Length);
Span<CieLab> pcsTo = pcsToBuffer.GetSpan();
CieXyz.FromScaledVector4(pcs, pcsFrom);
pcsConverter.Convert<CieXyz, CieLab>(pcsFrom, pcsTo);
CieLab.ToScaledVector4(pcsTo, pcs);
if (targetParams.Is16BitLutEntry)
{
LabToLabV2(pcs, pcs);
}
break;
}
// Convert from XYZ to XYZ.
case IccColorSpaceType.CieXyz when targetParams.PcsType is IccColorSpaceType.CieXyz:
{
using IMemoryOwner<CieXyz> pcsFromToBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieXyz>(pcs.Length);
Span<CieXyz> pcsFromTo = pcsFromToBuffer.GetSpan();
CieXyz.FromScaledVector4(pcs, pcsFromTo);
pcsConverter.Convert<CieXyz, CieXyz>(pcsFromTo, pcsFromTo);
CieXyz.ToScaledVector4(pcsFromTo, pcs);
break;
}
// Convert from Lab to Lab.
case IccColorSpaceType.CieLab when targetParams.PcsType is IccColorSpaceType.CieLab:
{
using IMemoryOwner<CieLab> pcsFromToBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieLab>(pcs.Length);
Span<CieLab> pcsFromTo = pcsFromToBuffer.GetSpan();
// if both source and target LUT use same v2 LAB encoding, no need to correct them
if (sourceParams.Is16BitLutEntry && targetParams.Is16BitLutEntry)
{
CieLab.FromScaledVector4(pcs, pcsFromTo);
pcsConverter.Convert<CieLab, CieLab>(pcsFromTo, pcsFromTo);
CieLab.ToScaledVector4(pcsFromTo, pcs);
}
else
{
if (sourceParams.Is16BitLutEntry)
{
LabV2ToLab(pcs, pcs);
}
CieLab.FromScaledVector4(pcs, pcsFromTo);
pcsConverter.Convert<CieLab, CieLab>(pcsFromTo, pcsFromTo);
CieLab.ToScaledVector4(pcsFromTo, pcs);
if (targetParams.Is16BitLutEntry)
{
LabToLabV2(pcs, pcs);
}
}
break;
}
default:
throw new ArgumentOutOfRangeException($"Source PCS {sourceParams.PcsType} to target PCS {targetParams.PcsType} is not supported");
}
}
/// <summary>
/// Effectively this is <see cref="GetTargetPcsWithoutAdjustment(Vector4, ConversionParams, ConversionParams, ColorProfileConverter)"/> with an extra step in the middle.
/// It adjusts PCS by compensating for the black point used for perceptual intent in v2 profiles.
/// The adjustment needs to be performed in XYZ space, potentially an overhead of 2 more conversions.
/// Not required if both spaces need V2 correction, since they both have the same understanding of the PCS.
/// Not compatible with PCS adjustment for absolute intent.
/// </summary>
/// <param name="sourcePcs">The source PCS values.</param>
/// <param name="sourceParams">The source profile parameters.</param>
/// <param name="targetParams">The target profile parameters.</param>
/// <param name="pcsConverter">The converter to use for the PCS adjustments.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the source or target PCS is not supported.</exception>
private static Vector4 GetTargetPcsWithPerceptualAdjustment(
Vector4 sourcePcs,
ConversionParams sourceParams,
ConversionParams targetParams,
ColorProfileConverter pcsConverter)
{
// all conversions are funneled through XYZ in case PCS adjustments need to be made
CieXyz xyz;
switch (sourceParams.PcsType)
{
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so convert Lab to modern v4 encoding when returned from a 16-bit LUT
case IccColorSpaceType.CieLab:
sourcePcs = sourceParams.Is16BitLutEntry ? LabV2ToLab(sourcePcs) : sourcePcs;
CieLab lab = CieLab.FromScaledVector4(sourcePcs);
xyz = pcsConverter.Convert<CieLab, CieXyz>(in lab);
break;
case IccColorSpaceType.CieXyz:
xyz = CieXyz.FromScaledVector4(sourcePcs);
break;
default:
throw new ArgumentOutOfRangeException($"Source PCS {sourceParams.PcsType} is not supported");
}
bool oneProfileHasV2PerceptualAdjustment = sourceParams.HasV2PerceptualHandling ^ targetParams.HasV2PerceptualHandling;
// when converting from device to PCS with v2 perceptual intent
// the black point needs to be adjusted to v4 after converting the PCS values
if (sourceParams.HasNoPerceptualHandling ||
(oneProfileHasV2PerceptualAdjustment && sourceParams.HasV2PerceptualHandling))
{
Vector3 vector = xyz.ToVector3();
// when using LAB PCS, negative values are clipped before PCS adjustment (in DemoIccMAX)
if (sourceParams.PcsType == IccColorSpaceType.CieLab)
{
vector = Vector3.Max(vector, Vector3.Zero);
}
xyz = new CieXyz(AdjustPcsFromV2BlackPoint(vector));
}
// when converting from PCS to device with v2 perceptual intent
// the black point needs to be adjusted to v2 before converting the PCS values
if (targetParams.HasNoPerceptualHandling ||
(oneProfileHasV2PerceptualAdjustment && targetParams.HasV2PerceptualHandling))
{
Vector3 vector = AdjustPcsToV2BlackPoint(xyz.AsVector3Unsafe());
// when using XYZ PCS, negative values are clipped after PCS adjustment (in DemoIccMAX)
if (targetParams.PcsType == IccColorSpaceType.CieXyz)
{
vector = Vector3.Max(vector, Vector3.Zero);
}
xyz = new CieXyz(vector);
}
switch (targetParams.PcsType)
{
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so convert Lab back to legacy encoding before using in a 16-bit LUT
case IccColorSpaceType.CieLab:
CieLab lab = pcsConverter.Convert<CieXyz, CieLab>(in xyz);
Vector4 targetPcs = lab.ToScaledVector4();
return targetParams.Is16BitLutEntry ? LabToLabV2(targetPcs) : targetPcs;
case IccColorSpaceType.CieXyz:
return xyz.ToScaledVector4();
default:
throw new ArgumentOutOfRangeException($"Target PCS {targetParams.PcsType} is not supported");
}
}
/// <summary>
/// Effectively this is <see cref="GetTargetPcsWithoutAdjustment(Span{Vector4}, ConversionParams, ConversionParams, ColorProfileConverter)"/> with an extra step in the middle.
/// It adjusts PCS by compensating for the black point used for perceptual intent in v2 profiles.
/// The adjustment needs to be performed in XYZ space, potentially an overhead of 2 more conversions.
/// Not required if both spaces need V2 correction, since they both have the same understanding of the PCS.
/// Not compatible with PCS adjustment for absolute intent.
/// </summary>
/// <param name="pcs">The PCS values from the source.</param>
/// <param name="sourceParams">The source profile parameters.</param>
/// <param name="targetParams">The target profile parameters.</param>
/// <param name="pcsConverter">The converter to use for the PCS adjustments.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the source or target PCS is not supported.</exception>
private static void GetTargetPcsWithPerceptualAdjustment(
Span<Vector4> pcs,
ConversionParams sourceParams,
ConversionParams targetParams,
ColorProfileConverter pcsConverter)
{
// All conversions are funneled through XYZ in case PCS adjustments need to be made
using IMemoryOwner<CieXyz> xyzBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieXyz>(pcs.Length);
Span<CieXyz> xyz = xyzBuffer.GetSpan();
switch (sourceParams.PcsType)
{
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so convert Lab to modern v4 encoding when returned from a 16-bit LUT
case IccColorSpaceType.CieLab:
{
if (sourceParams.Is16BitLutEntry)
{
LabV2ToLab(pcs, pcs);
}
using IMemoryOwner<CieLab> pcsFromBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieLab>(pcs.Length);
Span<CieLab> pcsFrom = pcsFromBuffer.GetSpan();
CieLab.FromScaledVector4(pcs, pcsFrom);
pcsConverter.Convert<CieLab, CieXyz>(pcsFrom, xyz);
break;
}
case IccColorSpaceType.CieXyz:
CieXyz.FromScaledVector4(pcs, xyz);
break;
default:
throw new ArgumentOutOfRangeException($"Source PCS {sourceParams.PcsType} is not supported");
}
bool oneProfileHasV2PerceptualAdjustment = sourceParams.HasV2PerceptualHandling ^ targetParams.HasV2PerceptualHandling;
using IMemoryOwner<Vector4> vectorBuffer = pcsConverter.Options.MemoryAllocator.Allocate<Vector4>(pcs.Length);
Span<Vector4> vector = vectorBuffer.GetSpan();
// When converting from device to PCS with v2 perceptual intent
// the black point needs to be adjusted to v4 after converting the PCS values
if (sourceParams.HasNoPerceptualHandling ||
(oneProfileHasV2PerceptualAdjustment && sourceParams.HasV2PerceptualHandling))
{
CieXyz.ToVector4(xyz, vector);
// When using LAB PCS, negative values are clipped before PCS adjustment (in DemoIccMAX)
if (sourceParams.PcsType == IccColorSpaceType.CieLab)
{
ClipNegative(vector);
}
AdjustPcsFromV2BlackPoint(vector, vector);
CieXyz.FromVector4(vector, xyz);
}
// When converting from PCS to device with v2 perceptual intent
// the black point needs to be adjusted to v2 before converting the PCS values
if (targetParams.HasNoPerceptualHandling ||
(oneProfileHasV2PerceptualAdjustment && targetParams.HasV2PerceptualHandling))
{
CieXyz.ToVector4(xyz, vector);
AdjustPcsToV2BlackPoint(vector, vector);
// When using XYZ PCS, negative values are clipped after PCS adjustment (in DemoIccMAX)
if (targetParams.PcsType == IccColorSpaceType.CieXyz)
{
ClipNegative(vector);
}
CieXyz.FromVector4(vector, xyz);
}
switch (targetParams.PcsType)
{
// 16-bit Lab encodings changed from v2 to v4, but 16-bit LUTs always use the legacy encoding regardless of version
// so convert Lab back to legacy encoding before using in a 16-bit LUT
case IccColorSpaceType.CieLab:
{
using IMemoryOwner<CieLab> pcsToBuffer = pcsConverter.Options.MemoryAllocator.Allocate<CieLab>(pcs.Length);
Span<CieLab> pcsTo = pcsToBuffer.GetSpan();
pcsConverter.Convert<CieXyz, CieLab>(xyz, pcsTo);
CieLab.ToScaledVector4(pcsTo, pcs);
if (targetParams.Is16BitLutEntry)
{
LabToLabV2(pcs, pcs);
}
break;
}
case IccColorSpaceType.CieXyz:
CieXyz.ToScaledVector4(xyz, pcs);
break;
default:
throw new ArgumentOutOfRangeException($"Target PCS {targetParams.PcsType} is not supported");
}
}
// as per DemoIccMAX icPerceptual values in IccCmm.h
// refBlack = 0.00336F, 0.0034731F, 0.00287F
// refWhite = 0.9642F, 1.0000F, 0.8249F
// scale = 1 - (refBlack / refWhite)
// offset = refBlack
private static Vector3 AdjustPcsFromV2BlackPoint(Vector3 xyz)
=> (xyz * new Vector3(0.9965153F, 0.9965269F, 0.9965208F)) + new Vector3(0.00336F, 0.0034731F, 0.00287F);
// as per DemoIccMAX icPerceptual values in IccCmm.h
// refBlack = 0.00336F, 0.0034731F, 0.00287F
// refWhite = 0.9642F, 1.0000F, 0.8249F
// scale = 1 / (1 - (refBlack / refWhite))
// offset = -refBlack * scale
private static Vector3 AdjustPcsToV2BlackPoint(Vector3 xyz)
=> (xyz * new Vector3(1.0034969F, 1.0034852F, 1.0034913F)) - new Vector3(0.0033717495F, 0.0034852044F, 0.0028800198F);
private static void AdjustPcsFromV2BlackPoint(Span<Vector4> source, Span<Vector4> destination)
{
if (Vector.IsHardwareAccelerated && Vector<float>.IsSupported &&
Vector<float>.Count <= Vector512<float>.Count &&
source.Length * 4 >= Vector<float>.Count)
{
// TODO: Check our constants. They may require scaling.
Vector<float> vScale = new(PcsV2FromBlackPointScale.AsSpan()[..Vector<float>.Count]);
Vector<float> vOffset = new(PcsV2FromBlackPointOffset.AsSpan()[..Vector<float>.Count]);
// SIMD loop
int i = 0;
int simdBatchSize = Vector<float>.Count / 4; // Number of Vector4 elements per SIMD batch
for (; i <= source.Length - simdBatchSize; i += simdBatchSize)
{
// Load the vector from source span
Vector<float> v = Unsafe.ReadUnaligned<Vector<float>>(ref Unsafe.As<Vector4, byte>(ref source[i]));
// Scale and offset the vector
v *= vScale;
v += vOffset;
// Write the vector to the destination span
Unsafe.WriteUnaligned(ref Unsafe.As<Vector4, byte>(ref destination[i]), v);
}
// Scalar fallback for remaining elements
for (; i < source.Length; i++)
{
Vector4 s = source[i];
s *= new Vector4(0.9965153F, 0.9965269F, 0.9965208F, 1F);
s += new Vector4(0.00336F, 0.0034731F, 0.00287F, 0F);
destination[i] = s;
}
}
else
{
// Scalar fallback if SIMD is not supported
for (int i = 0; i < source.Length; i++)
{
Vector4 s = source[i];
s *= new Vector4(0.9965153F, 0.9965269F, 0.9965208F, 1F);
s += new Vector4(0.00336F, 0.0034731F, 0.00287F, 0F);
destination[i] = s;
}
}
}
private static void AdjustPcsToV2BlackPoint(Span<Vector4> source, Span<Vector4> destination)
{
if (Vector.IsHardwareAccelerated && Vector<float>.IsSupported &&
Vector<float>.Count <= Vector512<float>.Count &&
source.Length * 4 >= Vector<float>.Count)
{
// TODO: Check our constants. They may require scaling.
Vector<float> vScale = new(PcsV2ToBlackPointScale.AsSpan()[..Vector<float>.Count]);
Vector<float> vOffset = new(PcsV2ToBlackPointOffset.AsSpan()[..Vector<float>.Count]);
// SIMD loop
int i = 0;
int simdBatchSize = Vector<float>.Count / 4; // Number of Vector4 elements per SIMD batch
for (; i <= source.Length - simdBatchSize; i += simdBatchSize)
{
// Load the vector from source span
Vector<float> v = Unsafe.ReadUnaligned<Vector<float>>(ref Unsafe.As<Vector4, byte>(ref source[i]));
// Scale and offset the vector
v *= vScale;
v -= vOffset;
// Write the vector to the destination span
Unsafe.WriteUnaligned(ref Unsafe.As<Vector4, byte>(ref destination[i]), v);
}
// Scalar fallback for remaining elements
for (; i < source.Length; i++)
{
Vector4 s = source[i];
s *= new Vector4(1.0034969F, 1.0034852F, 1.0034913F, 1F);
s -= new Vector4(0.0033717495F, 0.0034852044F, 0.0028800198F, 0F);
destination[i] = s;
}
}
else
{
// Scalar fallback if SIMD is not supported
for (int i = 0; i < source.Length; i++)
{
Vector4 s = source[i];
s *= new Vector4(1.0034969F, 1.0034852F, 1.0034913F, 1F);
s -= new Vector4(0.0033717495F, 0.0034852044F, 0.0028800198F, 0F);
destination[i] = s;
}
}
}
private static void ClipNegative(Span<Vector4> source)
{
if (Vector.IsHardwareAccelerated && Vector<float>.IsSupported && Vector<float>.Count >= source.Length * 4)
{
// SIMD loop
int i = 0;
int simdBatchSize = Vector<float>.Count / 4; // Number of Vector4 elements per SIMD batch
for (; i <= source.Length - simdBatchSize; i += simdBatchSize)
{
// Load the vector from source span
Vector<float> v = Unsafe.ReadUnaligned<Vector<float>>(ref Unsafe.As<Vector4, byte>(ref source[i]));
v = Vector.Max(v, Vector<float>.Zero);
// Write the vector to the destination span
Unsafe.WriteUnaligned(ref Unsafe.As<Vector4, byte>(ref source[i]), v);
}
// Scalar fallback for remaining elements
for (; i < source.Length; i++)
{
ref Vector4 s = ref source[i];
s = Vector4.Max(s, Vector4.Zero);
}
}
else
{
// Scalar fallback if SIMD is not supported
for (int i = 0; i < source.Length; i++)
{
ref Vector4 s = ref source[i];
s = Vector4.Max(s, Vector4.Zero);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector4 LabToLabV2(Vector4 input)
=> input * 65280F / 65535F;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector4 LabV2ToLab(Vector4 input)
=> input * 65535F / 65280F;
private static void LabToLabV2(Span<Vector4> source, Span<Vector4> destination)
=> LabToLab(source, destination, 65280F / 65535F);
private static void LabV2ToLab(Span<Vector4> source, Span<Vector4> destination)
=> LabToLab(source, destination, 65535F / 65280F);
private static void LabToLab(Span<Vector4> source, Span<Vector4> destination, [ConstantExpected] float scale)
{
if (Vector.IsHardwareAccelerated && Vector<float>.IsSupported)
{
Vector<float> vScale = new(scale);
int i = 0;
// SIMD loop
int simdBatchSize = Vector<float>.Count / 4; // Number of Vector4 elements per SIMD batch
for (; i <= source.Length - simdBatchSize; i += simdBatchSize)
{
// Load the vector from source span
Vector<float> v = Unsafe.ReadUnaligned<Vector<float>>(ref Unsafe.As<Vector4, byte>(ref source[i]));
// Scale the vector
v *= vScale;
// Write the scaled vector to the destination span
Unsafe.WriteUnaligned(ref Unsafe.As<Vector4, byte>(ref destination[i]), v);
}
// Scalar fallback for remaining elements
for (; i < source.Length; i++)
{
destination[i] = source[i] * scale;
}
}
else
{
// Scalar fallback if SIMD is not supported
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i] * scale;
}
}
}
private class ConversionParams
{
private readonly IccProfile profile;
internal ConversionParams(IccProfile profile, bool toPcs)
{
this.profile = profile;
this.Converter = toPcs ? new IccDataToPcsConverter(profile) : new IccPcsToDataConverter(profile);
}
internal IccConverterBase Converter { get; }
internal IccProfileHeader Header => this.profile.Header;
internal IccRenderingIntent Intent => this.Header.RenderingIntent;
internal IccColorSpaceType PcsType => this.Header.ProfileConnectionSpace;
internal IccVersion Version => this.Header.Version;
internal bool HasV2PerceptualHandling => this.Intent == IccRenderingIntent.Perceptual && this.Version.Major == 2;
internal bool HasNoPerceptualHandling => this.Intent == IccRenderingIntent.Perceptual && this.Converter.IsTrc;
internal bool Is16BitLutEntry => this.Converter.Is16BitLutEntry;
}
}

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbCieLab.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsRgbCieLab
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -33,6 +38,12 @@ internal static class ColorProfileConverterExtensionsRgbCieLab
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, CieLab>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbCieXyz.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsRgbCieXyz
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -32,6 +37,12 @@ internal static class ColorProfileConverterExtensionsRgbCieXyz
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, CieXyz>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

11
src/ImageSharp/ColorProfiles/ColorProfileConverterExtensionsRgbRgb.cs

@ -12,6 +12,11 @@ internal static class ColorProfileConverterExtensionsRgbRgb
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
return converter.ConvertUsingIccProfile<TFrom, TTo>(source);
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS
@ -33,6 +38,12 @@ internal static class ColorProfileConverterExtensionsRgbRgb
where TFrom : struct, IColorProfile<TFrom, Rgb>
where TTo : struct, IColorProfile<TTo, Rgb>
{
if (converter.ShouldUseIccProfiles())
{
converter.ConvertUsingIccProfile(source, destination);
return;
}
ColorConversionOptions options = converter.Options;
// Convert to input PCS.

42
src/ImageSharp/ColorProfiles/Hsl.cs

@ -41,6 +41,16 @@ public readonly struct Hsl : IColorProfile<Hsl, Rgb>
this.L = vector.Z;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private Hsl(Vector3 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.H = vector.X;
this.S = vector.Y;
this.L = vector.Z;
}
/// <summary>
/// Gets the hue component.
/// <remarks>A value ranging between 0 and 360.</remarks>
@ -83,6 +93,38 @@ public readonly struct Hsl : IColorProfile<Hsl, Rgb>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Hsl left, Hsl right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
=> new(this.AsVector3Unsafe() / 360F, 1F);
/// <inheritdoc/>
public static Hsl FromScaledVector4(Vector4 source)
=> new(source.AsVector3() * 360F, true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Hsl> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Hsl> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static Hsl FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{

42
src/ImageSharp/ColorProfiles/Hsv.cs

@ -41,6 +41,16 @@ public readonly struct Hsv : IColorProfile<Hsv, Rgb>
this.V = vector.Z;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private Hsv(Vector3 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.H = vector.X;
this.S = vector.Y;
this.V = vector.Z;
}
/// <summary>
/// Gets the hue component.
/// <remarks>A value ranging between 0 and 360.</remarks>
@ -81,6 +91,38 @@ public readonly struct Hsv : IColorProfile<Hsv, Rgb>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Hsv left, Hsv right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
=> new(this.AsVector3Unsafe() / 360F, 1F);
/// <inheritdoc/>
public static Hsv FromScaledVector4(Vector4 source)
=> new(source.AsVector3() * 360F, true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Hsv> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Hsv> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static Hsv FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{

45
src/ImageSharp/ColorProfiles/HunterLab.cs

@ -80,6 +80,49 @@ public readonly struct HunterLab : IColorProfile<HunterLab, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(HunterLab left, HunterLab right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 += new Vector3(0, 128F, 128F);
v3 /= new Vector3(100F, 255F, 255F);
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public static HunterLab FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= new Vector3(100F, 255, 255);
v3 -= new Vector3(0, 128F, 128F);
return new HunterLab(v3);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<HunterLab> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<HunterLab> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static HunterLab FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
{
@ -127,7 +170,7 @@ public readonly struct HunterLab : IColorProfile<HunterLab, CieXyz>
{
// Conversion algorithm described here:
// http://en.wikipedia.org/wiki/Lab_color_space#Hunter_Lab
CieXyz whitePoint = options.WhitePoint;
CieXyz whitePoint = options.SourceWhitePoint;
float l = this.L, a = this.A, b = this.B;
float xn = whitePoint.X, yn = whitePoint.Y, zn = whitePoint.Z;

48
src/ImageSharp/ColorProfiles/IColorProfile.cs

@ -1,6 +1,8 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
@ -15,18 +17,60 @@ public interface IColorProfile
public static abstract ChromaticAdaptionWhitePointSource GetChromaticAdaptionWhitePointSource();
}
/// <summary>
/// Defines the contract for all color profiles.
/// </summary>
/// <typeparam name="TSelf">The type of color profile.</typeparam>
public interface IColorProfile<TSelf> : IColorProfile, IEquatable<TSelf>
where TSelf : IColorProfile<TSelf>
{
/// <summary>
/// Expands the pixel into a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and clamped between <value>0</value> and <value>1</value>.
/// The vector components are typically expanded in least to greatest significance order.
/// </summary>
/// <returns>The <see cref="Vector4"/>.</returns>
public Vector4 ToScaledVector4();
#pragma warning disable CA1000 // Do not declare static members on generic types
/// <summary>
/// Initializes the color instance from a generic a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and clamped between <value>0</value> and <value>1</value>.
/// </summary>
/// <param name="source">The vector to load the pixel from.</param>
/// <returns>The <typeparamref name="TSelf"/>.</returns>
public static abstract TSelf FromScaledVector4(Vector4 source);
/// <summary>
/// Converts the span of colors to a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and clamped between <value>0</value> and <value>1</value>.
/// </summary>
/// <param name="source">The color span to convert from.</param>
/// <param name="destination">The vector span to write the results to.</param>
public static abstract void ToScaledVector4(ReadOnlySpan<TSelf> source, Span<Vector4> destination);
/// <summary>
/// Converts the span of colors from a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and clamped between <value>0</value> and <value>1</value>.
/// </summary>
/// <param name="source">The vector span to convert from.</param>
/// <param name="destination">The color span to write the results to.</param>
public static abstract void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<TSelf> destination);
#pragma warning restore CA1000 // Do not declare static members on generic types
}
/// <summary>
/// Defines the contract for all color profiles.
/// </summary>
/// <typeparam name="TSelf">The type of color profile.</typeparam>
/// <typeparam name="TProfileSpace">The type of color profile connecting space.</typeparam>
public interface IColorProfile<TSelf, TProfileSpace> : IColorProfile, IEquatable<TSelf>
public interface IColorProfile<TSelf, TProfileSpace> : IColorProfile<TSelf>
where TSelf : IColorProfile<TSelf, TProfileSpace>
where TProfileSpace : struct, IProfileConnectingSpace
{
#pragma warning disable CA1000 // Do not declare static members on generic types
/// <summary>
/// Converts the color from the profile connection space.
/// Initializes the color instance from the profile connection space.
/// </summary>
/// <param name="options">The color profile conversion options.</param>
/// <param name="source">The color profile connecting space.</param>

506
src/ImageSharp/ColorProfiles/Icc/Calculators/ClutCalculator.cs

@ -0,0 +1,506 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
/// <summary>
/// Implements interpolation methods for color profile lookup tables.
/// Adapted from ICC Reference implementation:
/// https://github.com/InternationalColorConsortium/DemoIccMAX/blob/79ecb74135ad47bac7d42692905a079839b7e105/IccProfLib/IccTagLut.cpp
/// </summary>
internal class ClutCalculator : IVector4Calculator
{
private readonly int inputCount;
private readonly int outputCount;
private readonly float[] lut;
private readonly byte[] gridPointCount;
private readonly byte[] maxGridPoint;
private readonly int[] indexFactor;
private readonly int[] dimSize;
private readonly int nodeCount;
private readonly float[][] nodes;
private readonly float[] g;
private readonly uint[] ig;
private readonly float[] s;
private readonly float[] df;
private readonly uint[] nPower;
private int n000;
private int n001;
private int n010;
private int n011;
private int n100;
private int n101;
private int n110;
private int n111;
private int n1000;
public ClutCalculator(IccClut clut)
{
Guard.NotNull(clut, nameof(clut));
Guard.MustBeGreaterThan(clut.InputChannelCount, 0, nameof(clut.InputChannelCount));
Guard.MustBeGreaterThan(clut.OutputChannelCount, 0, nameof(clut.OutputChannelCount));
this.inputCount = clut.InputChannelCount;
this.outputCount = clut.OutputChannelCount;
this.g = new float[this.inputCount];
this.ig = new uint[this.inputCount];
this.s = new float[this.inputCount];
this.nPower = new uint[16];
this.lut = clut.Values;
this.nodeCount = (int)Math.Pow(2, clut.InputChannelCount);
this.df = new float[this.nodeCount];
this.nodes = new float[this.nodeCount][];
this.dimSize = new int[this.inputCount];
this.gridPointCount = clut.GridPointCount;
this.maxGridPoint = new byte[this.inputCount];
for (int i = 0; i < this.inputCount; i++)
{
this.maxGridPoint[i] = (byte)(this.gridPointCount[i] - 1);
}
this.dimSize[this.inputCount - 1] = this.outputCount;
for (int i = this.inputCount - 2; i >= 0; i--)
{
this.dimSize[i] = this.dimSize[i + 1] * this.gridPointCount[i + 1];
}
this.indexFactor = this.CalculateIndexFactor();
}
public unsafe Vector4 Calculate(Vector4 value)
{
Vector4 result = default;
switch (this.inputCount)
{
case 1:
this.Interpolate1d((float*)&value, (float*)&result);
break;
case 2:
this.Interpolate2d((float*)&value, (float*)&result);
break;
case 3:
this.Interpolate3d((float*)&value, (float*)&result);
break;
case 4:
this.Interpolate4d((float*)&value, (float*)&result);
break;
default:
this.InterpolateNd((float*)&value, (float*)&result);
break;
}
return result;
}
private int[] CalculateIndexFactor()
{
int[] factors = new int[16];
switch (this.inputCount)
{
case 1:
factors[0] = this.n000 = 0;
factors[1] = this.n001 = this.dimSize[0];
break;
case 2:
factors[0] = this.n000 = 0;
factors[1] = this.n001 = this.dimSize[0];
factors[2] = this.n010 = this.dimSize[1];
factors[3] = this.n011 = this.n001 + this.n010;
break;
case 3:
factors[0] = this.n000 = 0;
factors[1] = this.n001 = this.dimSize[0];
factors[2] = this.n010 = this.dimSize[1];
factors[3] = this.n011 = this.n001 + this.n010;
factors[4] = this.n100 = this.dimSize[2];
factors[5] = this.n101 = this.n100 + this.n001;
factors[6] = this.n110 = this.n100 + this.n010;
factors[7] = this.n111 = this.n110 + this.n001;
break;
case 4:
factors[0] = 0;
factors[1] = this.n001 = this.dimSize[0];
factors[2] = this.n010 = this.dimSize[1];
factors[3] = factors[2] + factors[1];
factors[4] = this.n100 = this.dimSize[2];
factors[5] = factors[4] + factors[1];
factors[6] = factors[4] + factors[2];
factors[7] = factors[4] + factors[3];
factors[8] = this.n1000 = this.dimSize[3];
factors[9] = factors[8] + factors[1];
factors[10] = factors[8] + factors[2];
factors[11] = factors[8] + factors[3];
factors[12] = factors[8] + factors[4];
factors[13] = factors[8] + factors[5];
factors[14] = factors[8] + factors[6];
factors[15] = factors[8] + factors[7];
break;
default:
// Initialize ND interpolation variables.
factors[0] = 0;
int count;
for (count = 0; count < this.inputCount; count++)
{
this.nPower[count] = (uint)(1 << (this.inputCount - 1 - count));
}
uint[] nPower = [0, 1];
count = 0;
int nFlag = 1;
for (uint j = 1; j < this.nodeCount; j++)
{
if (j == nPower[1])
{
factors[j] = this.dimSize[count];
nPower[0] = (uint)(1 << count);
count++;
nPower[1] = (uint)(1 << count);
nFlag = 1;
}
else
{
factors[j] = factors[nPower[0]] + factors[nFlag];
nFlag++;
}
}
break;
}
return factors;
}
/// <summary>
/// One dimensional interpolation function.
/// </summary>
/// <param name="srcPixel">The input pixel values, which will be interpolated.</param>
/// <param name="destPixel">The interpolated output pixels.</param>
private unsafe void Interpolate1d(float* srcPixel, float* destPixel)
{
byte mx = this.maxGridPoint[0];
float x = UnitClip(srcPixel[0]) * mx;
uint ix = (uint)x;
float u = x - ix;
if (ix == mx)
{
ix--;
u = 1.0f;
}
float nu = (float)(1.0 - u);
int i;
Span<float> p = this.lut.AsSpan((int)(ix * this.n001));
// Normalize grid units.
float dF0 = nu;
float dF1 = u;
int offset = 0;
for (i = 0; i < this.outputCount; i++)
{
destPixel[i] = (float)((p[offset + this.n000] * dF0) + (p[offset + this.n001] * dF1));
offset++;
}
}
/// <summary>
/// Two dimensional interpolation function.
/// </summary>
/// <param name="srcPixel">The input pixel values, which will be interpolated.</param>
/// <param name="destPixel">The interpolated output pixels.</param>
private unsafe void Interpolate2d(float* srcPixel, float* destPixel)
{
byte mx = this.maxGridPoint[0];
byte my = this.maxGridPoint[1];
float x = UnitClip(srcPixel[0]) * mx;
float y = UnitClip(srcPixel[1]) * my;
uint ix = (uint)x;
uint iy = (uint)y;
float u = x - ix;
float t = y - iy;
if (ix == mx)
{
ix--;
u = 1.0f;
}
if (iy == my)
{
iy--;
t = 1.0f;
}
float nt = (float)(1.0 - t);
float nu = (float)(1.0 - u);
int i;
Span<float> p = this.lut.AsSpan((int)((ix * this.n001) + (iy * this.n010)));
// Normalize grid units.
float dF0 = nt * nu;
float dF1 = nt * u;
float dF2 = t * nu;
float dF3 = t * u;
int offset = 0;
for (i = 0; i < this.outputCount; i++)
{
destPixel[i] = (float)((p[offset + this.n000] * dF0) + (p[offset + this.n001] * dF1) + (p[offset + this.n010] * dF2) + (p[offset + this.n011] * dF3));
offset++;
}
}
/// <summary>
/// Three dimensional interpolation function.
/// </summary>
/// <param name="srcPixel">The input pixel values, which will be interpolated.</param>
/// <param name="destPixel">The interpolated output pixels.</param>
private unsafe void Interpolate3d(float* srcPixel, float* destPixel)
{
byte mx = this.maxGridPoint[0];
byte my = this.maxGridPoint[1];
byte mz = this.maxGridPoint[2];
float x = UnitClip(srcPixel[0]) * mx;
float y = UnitClip(srcPixel[1]) * my;
float z = UnitClip(srcPixel[2]) * mz;
uint ix = (uint)x;
uint iy = (uint)y;
uint iz = (uint)z;
float u = x - ix;
float t = y - iy;
float s = z - iz;
if (ix == mx)
{
ix--;
u = 1.0f;
}
if (iy == my)
{
iy--;
t = 1.0f;
}
if (iz == mz)
{
iz--;
s = 1.0f;
}
float ns = (float)(1.0 - s);
float nt = (float)(1.0 - t);
float nu = (float)(1.0 - u);
Span<float> p = this.lut.AsSpan((int)((ix * this.n001) + (iy * this.n010) + (iz * this.n100)));
// Normalize grid units
float dF0 = ns * nt * nu;
float dF1 = ns * nt * u;
float dF2 = ns * t * nu;
float dF3 = ns * t * u;
float dF4 = s * nt * nu;
float dF5 = s * nt * u;
float dF6 = s * t * nu;
float dF7 = s * t * u;
int offset = 0;
for (int i = 0; i < this.outputCount; i++)
{
destPixel[i] = (float)((p[offset + this.n000] * dF0) +
(p[offset + this.n001] * dF1) +
(p[offset + this.n010] * dF2) +
(p[offset + this.n011] * dF3) +
(p[offset + this.n100] * dF4) +
(p[offset + this.n101] * dF5) +
(p[offset + this.n110] * dF6) +
(p[offset + this.n111] * dF7));
offset++;
}
}
/// <summary>
/// Four dimensional interpolation function.
/// </summary>
/// <param name="srcPixel">The input pixel values, which will be interpolated.</param>
/// <param name="destPixel">The interpolated output pixels.</param>
private unsafe void Interpolate4d(float* srcPixel, float* destPixel)
{
byte mw = this.maxGridPoint[0];
byte mx = this.maxGridPoint[1];
byte my = this.maxGridPoint[2];
byte mz = this.maxGridPoint[3];
float w = UnitClip(srcPixel[0]) * mw;
float x = UnitClip(srcPixel[1]) * mx;
float y = UnitClip(srcPixel[2]) * my;
float z = UnitClip(srcPixel[3]) * mz;
uint iw = (uint)w;
uint ix = (uint)x;
uint iy = (uint)y;
uint iz = (uint)z;
float v = w - iw;
float u = x - ix;
float t = y - iy;
float s = z - iz;
if (iw == mw)
{
iw--;
v = 1.0f;
}
if (ix == mx)
{
ix--;
u = 1.0f;
}
if (iy == my)
{
iy--;
t = 1.0f;
}
if (iz == mz)
{
iz--;
s = 1.0f;
}
float ns = (float)(1.0 - s);
float nt = (float)(1.0 - t);
float nu = (float)(1.0 - u);
float nv = (float)(1.0 - v);
Span<float> p = this.lut.AsSpan((int)((iw * this.n001) + (ix * this.n010) + (iy * this.n100) + (iz * this.n1000)));
// Normalize grid units.
float[] dF =
[
ns * nt * nu * nv,
ns * nt * nu * v,
ns * nt * u * nv,
ns * nt * u * v,
ns * t * nu * nv,
ns * t * nu * v,
ns * t * u * nv,
ns * t * u * v,
s * nt * nu * nv,
s * nt * nu * v,
s * nt * u * nv,
s * nt * u * v,
s * t * nu * nv,
s * t * nu * v,
s * t * u * nv,
s * t * u * v,
];
int offset = 0;
for (int i = 0; i < this.outputCount; i++)
{
float pv = 0.0f;
for (int j = 0; j < 16; j++)
{
pv += p[offset + this.indexFactor[j]] * dF[j];
}
destPixel[i] = pv;
offset++;
}
}
/// <summary>
/// Generic N-dimensional interpolation function.
/// </summary>
/// <param name="srcPixel">The input pixel values, which will be interpolated.</param>
/// <param name="destPixel">The interpolated output pixels.</param>
private unsafe void InterpolateNd(float* srcPixel, float* destPixel)
{
int index = 0;
for (int i = 0; i < this.inputCount; i++)
{
this.g[i] = UnitClip(srcPixel[i]) * this.maxGridPoint[i];
this.ig[i] = (uint)this.g[i];
this.s[this.inputCount - 1 - i] = this.g[i] - this.ig[i];
if (this.ig[i] == this.maxGridPoint[i])
{
this.ig[i]--;
this.s[this.inputCount - 1 - i] = 1.0f;
}
index += (int)this.ig[i] * this.dimSize[i];
}
Span<float> p = this.lut.AsSpan(index);
float[] temp = new float[2];
bool nFlag = false;
for (int i = 0; i < this.nodeCount; i++)
{
this.df[i] = 1.0f;
}
for (int i = 0; i < this.inputCount; i++)
{
temp[0] = 1.0f - this.s[i];
temp[1] = this.s[i];
index = (int)this.nPower[i];
for (int j = 0; j < this.nodeCount; j++)
{
this.df[j] *= temp[nFlag ? 1 : 0];
if ((j + 1) % index == 0)
{
nFlag = !nFlag;
}
}
nFlag = false;
}
int offset = 0;
for (int i = 0; i < this.outputCount; i++)
{
float pv = 0;
for (int j = 0; j < this.nodeCount; j++)
{
pv += p[offset + this.indexFactor[j]] * this.df[j];
}
destPixel[i] = pv;
offset++;
}
}
private static float UnitClip(float v)
{
if (v < 0)
{
return 0;
}
if (v > 1.0)
{
return 1.0f;
}
return v;
}
}

65
src/ImageSharp/ColorProfiles/Icc/Calculators/ColorTrcCalculator.cs

@ -0,0 +1,65 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class ColorTrcCalculator : IVector4Calculator
{
private readonly TrcCalculator curveCalculator;
private readonly Matrix4x4 matrix;
private readonly bool toPcs;
public ColorTrcCalculator(
IccXyzTagDataEntry redMatrixColumn,
IccXyzTagDataEntry greenMatrixColumn,
IccXyzTagDataEntry blueMatrixColumn,
IccTagDataEntry redTrc,
IccTagDataEntry greenTrc,
IccTagDataEntry blueTrc,
bool toPcs)
{
this.toPcs = toPcs;
this.curveCalculator = new TrcCalculator([redTrc, greenTrc, blueTrc], !toPcs);
Vector3 mr = redMatrixColumn.Data[0];
Vector3 mg = greenMatrixColumn.Data[0];
Vector3 mb = blueMatrixColumn.Data[0];
this.matrix = new Matrix4x4(mr.X, mr.Y, mr.Z, 0, mg.X, mg.Y, mg.Z, 0, mb.X, mb.Y, mb.Z, 0, 0, 0, 0, 1);
if (!toPcs)
{
Matrix4x4.Invert(this.matrix, out this.matrix);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 Calculate(Vector4 value)
{
if (this.toPcs)
{
// input is always linear RGB
value = this.curveCalculator.Calculate(value);
CieXyz xyz = new(Vector4.Transform(value, this.matrix).AsVector3());
// when data to PCS, output from calculator is descaled XYZ
// but downstream process requires scaled XYZ
// (see DemoMaxICC IccCmm.cpp : CIccXformMatrixTRC::Apply)
return xyz.ToScaledVector4();
}
else
{
// input is always XYZ
Vector4 xyz = Vector4.Transform(value, this.matrix);
// when data to PCS, upstream process provides scaled XYZ
// but input to calculator is descaled XYZ
// (see DemoMaxICC IccCmm.cpp : CIccXformMatrixTRC::Apply)
xyz = new(CieXyz.FromScaledVector4(xyz).AsVector3Unsafe(), 1);
return this.curveCalculator.Calculate(xyz);
}
}
}

14
src/ImageSharp/ColorProfiles/Icc/Calculators/CurveCalculator.CalculationType.cs

@ -0,0 +1,14 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
internal partial class CurveCalculator
{
private enum CalculationType
{
Identity,
Gamma,
Lut,
}
}

47
src/ImageSharp/ColorProfiles/Icc/Calculators/CurveCalculator.cs

@ -0,0 +1,47 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
internal partial class CurveCalculator : ISingleCalculator
{
private readonly LutCalculator lutCalculator;
private readonly float gamma;
private readonly CalculationType type;
public CurveCalculator(IccCurveTagDataEntry entry, bool inverted)
{
if (entry.IsIdentityResponse)
{
this.type = CalculationType.Identity;
}
else if (entry.IsGamma)
{
this.gamma = entry.Gamma;
if (inverted)
{
this.gamma = 1f / this.gamma;
}
this.type = CalculationType.Gamma;
}
else
{
this.lutCalculator = new LutCalculator(entry.CurveData, inverted);
this.type = CalculationType.Lut;
}
}
public float Calculate(float value)
=> this.type switch
{
CalculationType.Identity => value,
CalculationType.Gamma => MathF.Pow(value, this.gamma), // TODO: This could be optimized using a LUT. See SrgbCompanding
CalculationType.Lut => this.lutCalculator.Calculate(value),
_ => throw new InvalidOperationException("Invalid calculation type"),
};
}

19
src/ImageSharp/ColorProfiles/Icc/Calculators/GrayTrcCalculator.cs

@ -0,0 +1,19 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class GrayTrcCalculator : IVector4Calculator
{
private readonly TrcCalculator calculator;
public GrayTrcCalculator(IccTagDataEntry grayTrc, bool toPcs)
=> this.calculator = new TrcCalculator(new IccTagDataEntry[] { grayTrc }, !toPcs);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 Calculate(Vector4 value) => this.calculator.Calculate(value);
}

17
src/ImageSharp/ColorProfiles/Icc/Calculators/ISingleCalculator.cs

@ -0,0 +1,17 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
/// <summary>
/// Represents an ICC calculator with a single floating point value and result
/// </summary>
internal interface ISingleCalculator
{
/// <summary>
/// Calculates a result from the given value
/// </summary>
/// <param name="value">The input value</param>
/// <returns>The calculated result</returns>
float Calculate(float value);
}

19
src/ImageSharp/ColorProfiles/Icc/Calculators/IVector4Calculator.cs

@ -0,0 +1,19 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
/// <summary>
/// Represents an ICC calculator with <see cref="Vector4"/> values and results
/// </summary>
internal interface IVector4Calculator
{
/// <summary>
/// Calculates a result from the given values
/// </summary>
/// <param name="value">The input values</param>
/// <returns>The calculated result</returns>
Vector4 Calculate(Vector4 value);
}

18
src/ImageSharp/ColorProfiles/Icc/Calculators/LutABCalculator.CalculationType.cs

@ -0,0 +1,18 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
internal partial class LutABCalculator
{
private enum CalculationType
{
AtoB = 1 << 3,
BtoA = 1 << 4,
SingleCurve = 1,
CurveMatrix = 2,
CurveClut = 3,
Full = 4,
}
}

135
src/ImageSharp/ColorProfiles/Icc/Calculators/LutABCalculator.cs

@ -0,0 +1,135 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using System.Numerics;
using SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
internal partial class LutABCalculator : IVector4Calculator
{
private CalculationType type;
private TrcCalculator curveACalculator;
private TrcCalculator curveBCalculator;
private TrcCalculator curveMCalculator;
private MatrixCalculator matrixCalculator;
private ClutCalculator clutCalculator;
public LutABCalculator(IccLutAToBTagDataEntry entry)
{
Guard.NotNull(entry, nameof(entry));
this.Init(entry.CurveA, entry.CurveB, entry.CurveM, entry.Matrix3x1, entry.Matrix3x3, entry.ClutValues);
this.type |= CalculationType.AtoB;
}
public LutABCalculator(IccLutBToATagDataEntry entry)
{
Guard.NotNull(entry, nameof(entry));
this.Init(entry.CurveA, entry.CurveB, entry.CurveM, entry.Matrix3x1, entry.Matrix3x3, entry.ClutValues);
this.type |= CalculationType.BtoA;
}
public Vector4 Calculate(Vector4 value)
{
switch (this.type)
{
case CalculationType.Full | CalculationType.AtoB:
value = this.curveACalculator.Calculate(value);
value = this.clutCalculator.Calculate(value);
value = this.curveMCalculator.Calculate(value);
value = this.matrixCalculator.Calculate(value);
return this.curveBCalculator.Calculate(value);
case CalculationType.Full | CalculationType.BtoA:
value = this.curveBCalculator.Calculate(value);
value = this.matrixCalculator.Calculate(value);
value = this.curveMCalculator.Calculate(value);
value = this.clutCalculator.Calculate(value);
return this.curveACalculator.Calculate(value);
case CalculationType.CurveClut | CalculationType.AtoB:
value = this.curveACalculator.Calculate(value);
value = this.clutCalculator.Calculate(value);
return this.curveBCalculator.Calculate(value);
case CalculationType.CurveClut | CalculationType.BtoA:
value = this.curveBCalculator.Calculate(value);
value = this.clutCalculator.Calculate(value);
return this.curveACalculator.Calculate(value);
case CalculationType.CurveMatrix | CalculationType.AtoB:
value = this.curveMCalculator.Calculate(value);
value = this.matrixCalculator.Calculate(value);
return this.curveBCalculator.Calculate(value);
case CalculationType.CurveMatrix | CalculationType.BtoA:
value = this.curveBCalculator.Calculate(value);
value = this.matrixCalculator.Calculate(value);
return this.curveMCalculator.Calculate(value);
case CalculationType.SingleCurve | CalculationType.AtoB:
case CalculationType.SingleCurve | CalculationType.BtoA:
return this.curveBCalculator.Calculate(value);
default:
throw new InvalidOperationException("Invalid calculation type");
}
}
private void Init(IccTagDataEntry[] curveA, IccTagDataEntry[] curveB, IccTagDataEntry[] curveM, Vector3? matrix3x1, Matrix4x4? matrix3x3, IccClut clut)
{
bool hasACurve = curveA != null;
bool hasBCurve = curveB != null;
bool hasMCurve = curveM != null;
bool hasMatrix = matrix3x1 != null && matrix3x3 != null;
bool hasClut = clut != null;
if (hasBCurve && hasMatrix && hasMCurve && hasClut && hasACurve)
{
this.type = CalculationType.Full;
}
else if (hasBCurve && hasClut && hasACurve)
{
this.type = CalculationType.CurveClut;
}
else if (hasBCurve && hasMatrix && hasMCurve)
{
this.type = CalculationType.CurveMatrix;
}
else if (hasBCurve)
{
this.type = CalculationType.SingleCurve;
}
else
{
throw new InvalidIccProfileException("AToB or BToA tag has an invalid configuration");
}
if (hasACurve)
{
this.curveACalculator = new TrcCalculator(curveA, false);
}
if (hasBCurve)
{
this.curveBCalculator = new TrcCalculator(curveB, false);
}
if (hasMCurve)
{
this.curveMCalculator = new TrcCalculator(curveM, false);
}
if (hasMatrix)
{
this.matrixCalculator = new MatrixCalculator(matrix3x3.Value, matrix3x1.Value);
}
if (hasClut)
{
this.clutCalculator = new ClutCalculator(clut);
}
}
}

77
src/ImageSharp/ColorProfiles/Icc/Calculators/LutCalculator.cs

@ -0,0 +1,77 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class LutCalculator : ISingleCalculator
{
private readonly float[] lut;
private readonly bool inverse;
public LutCalculator(float[] lut, bool inverse)
{
Guard.NotNull(lut, nameof(lut));
this.lut = lut;
this.inverse = inverse;
}
public float Calculate(float value)
{
if (this.inverse)
{
return this.LookupInverse(value);
}
return this.Lookup(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float Lookup(float value)
{
value = Math.Max(value, 0);
float factor = value * (this.lut.Length - 1);
int index = (int)factor;
float low = this.lut[index];
float high = 1F;
if (index < this.lut.Length - 1)
{
high = this.lut[index + 1];
}
return low + ((high - low) * (factor - index));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float LookupInverse(float value)
{
int index = Array.BinarySearch(this.lut, value);
if (index >= 0)
{
return index / (float)(this.lut.Length - 1);
}
index = ~index;
if (index == 0)
{
return 0;
}
else if (index == this.lut.Length)
{
return 1;
}
float high = this.lut[index];
float low = this.lut[index - 1];
float valuePercent = (value - low) / (high - low);
float lutRange = 1 / (float)(this.lut.Length - 1);
float lutLow = (index - 1) / (float)(this.lut.Length - 1);
return lutLow + (valuePercent * lutRange);
}
}

80
src/ImageSharp/ColorProfiles/Icc/Calculators/LutEntryCalculator.cs

@ -0,0 +1,80 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class LutEntryCalculator : IVector4Calculator
{
private LutCalculator[] inputCurve;
private LutCalculator[] outputCurve;
private ClutCalculator clutCalculator;
private Matrix4x4 matrix;
private bool doTransform;
public LutEntryCalculator(IccLut8TagDataEntry lut)
{
Guard.NotNull(lut, nameof(lut));
this.Init(lut.InputValues, lut.OutputValues, lut.ClutValues, lut.Matrix);
this.Is16Bit = false;
}
public LutEntryCalculator(IccLut16TagDataEntry lut)
{
Guard.NotNull(lut, nameof(lut));
this.Init(lut.InputValues, lut.OutputValues, lut.ClutValues, lut.Matrix);
this.Is16Bit = true;
}
internal bool Is16Bit { get; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 Calculate(Vector4 value)
{
if (this.doTransform)
{
value = Vector4.Transform(value, this.matrix);
}
value = CalculateLut(this.inputCurve, value);
value = this.clutCalculator.Calculate(value);
return CalculateLut(this.outputCurve, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector4 CalculateLut(LutCalculator[] lut, Vector4 value)
{
ref float f = ref Unsafe.As<Vector4, float>(ref value);
for (int i = 0; i < lut.Length; i++)
{
Unsafe.Add(ref f, i) = lut[i].Calculate(Unsafe.Add(ref f, i));
}
return value;
}
private void Init(IccLut[] inputCurve, IccLut[] outputCurve, IccClut clut, Matrix4x4 matrix)
{
this.inputCurve = InitLut(inputCurve);
this.outputCurve = InitLut(outputCurve);
this.clutCalculator = new ClutCalculator(clut);
this.matrix = matrix;
this.doTransform = !matrix.IsIdentity && inputCurve.Length == 3;
}
private static LutCalculator[] InitLut(IccLut[] curves)
{
LutCalculator[] calculators = new LutCalculator[curves.Length];
for (int i = 0; i < curves.Length; i++)
{
calculators[i] = new LutCalculator(curves[i].Values, false);
}
return calculators;
}
}

26
src/ImageSharp/ColorProfiles/Icc/Calculators/MatrixCalculator.cs

@ -0,0 +1,26 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class MatrixCalculator : IVector4Calculator
{
private Matrix4x4 matrix2D;
private Vector4 matrix1D;
public MatrixCalculator(Matrix4x4 matrix3x3, Vector3 matrix3x1)
{
this.matrix2D = matrix3x3;
this.matrix1D = new Vector4(matrix3x1, 0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 Calculate(Vector4 value)
{
Vector4 transformed = Vector4.Transform(value, this.matrix2D);
return Vector4.Add(this.matrix1D, transformed);
}
}

130
src/ImageSharp/ColorProfiles/Icc/Calculators/ParametricCurveCalculator.cs

@ -0,0 +1,130 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class ParametricCurveCalculator : ISingleCalculator
{
private readonly IccParametricCurve curve;
private readonly IccParametricCurveType type;
private const IccParametricCurveType InvertedFlag = (IccParametricCurveType)(1 << 3);
public ParametricCurveCalculator(IccParametricCurveTagDataEntry entry, bool inverted)
{
Guard.NotNull(entry, nameof(entry));
this.curve = entry.Curve;
this.type = entry.Curve.Type;
if (inverted)
{
this.type |= InvertedFlag;
}
}
public float Calculate(float value)
=> this.type switch
{
IccParametricCurveType.Type1 => this.CalculateGamma(value),
IccParametricCurveType.Cie122_1996 => this.CalculateCie122(value),
IccParametricCurveType.Iec61966_3 => this.CalculateIec61966(value),
IccParametricCurveType.SRgb => this.CalculateSRgb(value),
IccParametricCurveType.Type5 => this.CalculateType5(value),
IccParametricCurveType.Type1 | InvertedFlag => this.CalculateInvertedGamma(value),
IccParametricCurveType.Cie122_1996 | InvertedFlag => this.CalculateInvertedCie122(value),
IccParametricCurveType.Iec61966_3 | InvertedFlag => this.CalculateInvertedIec61966(value),
IccParametricCurveType.SRgb | InvertedFlag => this.CalculateInvertedSRgb(value),
IccParametricCurveType.Type5 | InvertedFlag => this.CalculateInvertedType5(value),
_ => throw new InvalidIccProfileException("ParametricCurve"),
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateGamma(float value) => MathF.Pow(value, this.curve.G);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateCie122(float value)
{
if (value >= -this.curve.B / this.curve.A)
{
return MathF.Pow((this.curve.A * value) + this.curve.B, this.curve.G);
}
return 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateIec61966(float value)
{
if (value >= -this.curve.B / this.curve.A)
{
return MathF.Pow((this.curve.A * value) + this.curve.B, this.curve.G) + this.curve.C;
}
return this.curve.C;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateSRgb(float value)
{
if (value >= this.curve.D)
{
return MathF.Pow((this.curve.A * value) + this.curve.B, this.curve.G);
}
return this.curve.C * value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateType5(float value)
{
if (value >= this.curve.D)
{
return MathF.Pow((this.curve.A * value) + this.curve.B, this.curve.G) + this.curve.E;
}
return (this.curve.C * value) + this.curve.F;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateInvertedGamma(float value)
=> MathF.Pow(value, 1 / this.curve.G);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateInvertedCie122(float value)
=> (MathF.Pow(value, 1 / this.curve.G) - this.curve.B) / this.curve.A;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateInvertedIec61966(float value)
{
if (value >= this.curve.C)
{
return (MathF.Pow(value - this.curve.C, 1 / this.curve.G) - this.curve.B) / this.curve.A;
}
return -this.curve.B / this.curve.A;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateInvertedSRgb(float value)
{
if (value >= MathF.Pow((this.curve.A * this.curve.D) + this.curve.B, this.curve.G))
{
return (MathF.Pow(value, 1 / this.curve.G) - this.curve.B) / this.curve.A;
}
return value / this.curve.C;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private float CalculateInvertedType5(float value)
{
if (value >= (this.curve.C * this.curve.D) + this.curve.F)
{
return (MathF.Pow(value - this.curve.E, 1 / this.curve.G) - this.curve.B) / this.curve.A;
}
return (value - this.curve.F) / this.curve.C;
}
}

41
src/ImageSharp/ColorProfiles/Icc/Calculators/TrcCalculator.cs

@ -0,0 +1,41 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
internal class TrcCalculator : IVector4Calculator
{
private readonly ISingleCalculator[] calculators;
public TrcCalculator(IccTagDataEntry[] entries, bool inverted)
{
Guard.NotNull(entries, nameof(entries));
this.calculators = new ISingleCalculator[entries.Length];
for (int i = 0; i < entries.Length; i++)
{
this.calculators[i] = entries[i] switch
{
IccCurveTagDataEntry curve => new CurveCalculator(curve, inverted),
IccParametricCurveTagDataEntry parametricCurve => new ParametricCurveCalculator(parametricCurve, inverted),
_ => throw new InvalidIccProfileException("Invalid Entry."),
};
}
}
public unsafe Vector4 Calculate(Vector4 value)
{
ref float f = ref Unsafe.As<Vector4, float>(ref value);
for (int i = 0; i < this.calculators.Length; i++)
{
Unsafe.Add(ref f, i) = this.calculators[i].Calculate(Unsafe.Add(ref f, i));
}
return value;
}
}

155
src/ImageSharp/ColorProfiles/Icc/IccConverterBase.Checks.cs

@ -0,0 +1,155 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal abstract partial class IccConverterBase
{
private static ConversionMethod GetConversionMethod(IccProfile profile, IccRenderingIntent renderingIntent) => profile.Header.Class switch
{
IccProfileClass.InputDevice or
IccProfileClass.DisplayDevice or
IccProfileClass.OutputDevice or
IccProfileClass.ColorSpace => CheckMethod1(profile, renderingIntent),
IccProfileClass.DeviceLink or IccProfileClass.Abstract => CheckMethod2(profile),
_ => ConversionMethod.Invalid,
};
private static ConversionMethod CheckMethod1(IccProfile profile, IccRenderingIntent renderingIntent)
{
ConversionMethod method = CheckMethodD(profile, renderingIntent);
if (method != ConversionMethod.Invalid)
{
return method;
}
method = CheckMethodA(profile, renderingIntent);
if (method != ConversionMethod.Invalid)
{
return method;
}
method = CheckMethodA0(profile);
if (method != ConversionMethod.Invalid)
{
return method;
}
method = CheckMethodTrc(profile);
if (method != ConversionMethod.Invalid)
{
return method;
}
return ConversionMethod.Invalid;
}
private static ConversionMethod CheckMethodD(IccProfile profile, IccRenderingIntent renderingIntent)
{
if ((HasTag(profile, IccProfileTag.DToB0) || HasTag(profile, IccProfileTag.BToD0))
&& renderingIntent == IccRenderingIntent.Perceptual)
{
return ConversionMethod.D0;
}
if ((HasTag(profile, IccProfileTag.DToB1) || HasTag(profile, IccProfileTag.BToD1))
&& renderingIntent == IccRenderingIntent.MediaRelativeColorimetric)
{
return ConversionMethod.D1;
}
if ((HasTag(profile, IccProfileTag.DToB2) || HasTag(profile, IccProfileTag.BToD2))
&& renderingIntent == IccRenderingIntent.Saturation)
{
return ConversionMethod.D2;
}
if ((HasTag(profile, IccProfileTag.DToB3) || HasTag(profile, IccProfileTag.BToD3))
&& renderingIntent == IccRenderingIntent.AbsoluteColorimetric)
{
return ConversionMethod.D3;
}
return ConversionMethod.Invalid;
}
private static ConversionMethod CheckMethodA(IccProfile profile, IccRenderingIntent renderingIntent)
{
if ((HasTag(profile, IccProfileTag.AToB0) || HasTag(profile, IccProfileTag.BToA0))
&& renderingIntent == IccRenderingIntent.Perceptual)
{
return ConversionMethod.A0;
}
if ((HasTag(profile, IccProfileTag.AToB1) || HasTag(profile, IccProfileTag.BToA1))
&& renderingIntent == IccRenderingIntent.MediaRelativeColorimetric)
{
return ConversionMethod.A1;
}
if ((HasTag(profile, IccProfileTag.AToB2) || HasTag(profile, IccProfileTag.BToA2))
&& renderingIntent == IccRenderingIntent.Saturation)
{
return ConversionMethod.A2;
}
return ConversionMethod.Invalid;
}
private static ConversionMethod CheckMethodA0(IccProfile profile)
{
bool valid = HasTag(profile, IccProfileTag.AToB0) || HasTag(profile, IccProfileTag.BToA0);
return valid ? ConversionMethod.A0 : ConversionMethod.Invalid;
}
private static ConversionMethod CheckMethodTrc(IccProfile profile)
{
if (HasTag(profile, IccProfileTag.RedMatrixColumn)
&& HasTag(profile, IccProfileTag.GreenMatrixColumn)
&& HasTag(profile, IccProfileTag.BlueMatrixColumn)
&& HasTag(profile, IccProfileTag.RedTrc)
&& HasTag(profile, IccProfileTag.GreenTrc)
&& HasTag(profile, IccProfileTag.BlueTrc))
{
return ConversionMethod.ColorTrc;
}
if (HasTag(profile, IccProfileTag.GrayTrc))
{
return ConversionMethod.GrayTrc;
}
return ConversionMethod.Invalid;
}
private static ConversionMethod CheckMethod2(IccProfile profile)
{
if (HasTag(profile, IccProfileTag.DToB0) || HasTag(profile, IccProfileTag.BToD0))
{
return ConversionMethod.D0;
}
if (HasTag(profile, IccProfileTag.AToB0) || HasTag(profile, IccProfileTag.AToB0))
{
return ConversionMethod.A0;
}
return ConversionMethod.Invalid;
}
private static bool HasTag(IccProfile profile, IccProfileTag tag)
=> profile.Entries.Any(t => t.TagSignature == tag);
private static IccTagDataEntry GetTag(IccProfile profile, IccProfileTag tag)
=> Array.Find(profile.Entries, t => t.TagSignature == tag);
private static T GetTag<T>(IccProfile profile, IccProfileTag tag)
where T : IccTagDataEntry
=> profile.Entries.OfType<T>().FirstOrDefault(t => t.TagSignature == tag);
}

66
src/ImageSharp/ColorProfiles/Icc/IccConverterBase.ConversionMethod.cs

@ -0,0 +1,66 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal abstract partial class IccConverterBase
{
/// <summary>
/// Conversion methods with ICC profiles
/// </summary>
private enum ConversionMethod
{
/// <summary>
/// Conversion using anything but Multi Process Elements with perceptual rendering intent
/// </summary>
A0,
/// <summary>
/// Conversion using anything but Multi Process Elements with relative colorimetric rendering intent
/// </summary>
A1,
/// <summary>
/// Conversion using anything but Multi Process Elements with saturation rendering intent
/// </summary>
A2,
/// <summary>
/// Conversion using Multi Process Elements with perceptual rendering intent
/// </summary>
D0,
/// <summary>
/// Conversion using Multi Process Elements with relative colorimetric rendering intent
/// </summary>
D1,
/// <summary>
/// Conversion using Multi Process Elements with saturation rendering intent
/// </summary>
D2,
/// <summary>
/// Conversion using Multi Process Elements with absolute colorimetric rendering intent
/// </summary>
D3,
/// <summary>
/// Conversion of more than one channel using tone reproduction curves
/// </summary>
ColorTrc,
/// <summary>
/// Conversion of exactly one channel using a tone reproduction curve
/// </summary>
GrayTrc,
/// <summary>
/// No valid conversion method available or found
/// </summary>
Invalid,
}
}

109
src/ImageSharp/ColorProfiles/Icc/IccConverterbase.Conversions.cs

@ -0,0 +1,109 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.ColorProfiles.Icc.Calculators;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal abstract partial class IccConverterBase
{
private IVector4Calculator calculator;
internal bool Is16BitLutEntry => this.calculator is LutEntryCalculator { Is16Bit: true };
internal bool IsTrc => this.calculator is ColorTrcCalculator or GrayTrcCalculator;
/// <summary>
/// Checks the profile for available conversion methods and gathers all the information's necessary for it.
/// </summary>
/// <param name="profile">The profile to use for the conversion.</param>
/// <param name="toPcs">True if the conversion is to the Profile Connection Space.</param>
/// <param name="renderingIntent">The wanted rendering intent. Can be ignored if not available.</param>
/// <exception cref="InvalidIccProfileException">Invalid conversion method.</exception>
protected void Init(IccProfile profile, bool toPcs, IccRenderingIntent renderingIntent)
=> this.calculator = GetConversionMethod(profile, renderingIntent) switch
{
ConversionMethod.D0 => toPcs ?
InitD(profile, IccProfileTag.DToB0) :
InitD(profile, IccProfileTag.BToD0),
ConversionMethod.D1 => toPcs ?
InitD(profile, IccProfileTag.DToB1) :
InitD(profile, IccProfileTag.BToD1),
ConversionMethod.D2 => toPcs ?
InitD(profile, IccProfileTag.DToB2) :
InitD(profile, IccProfileTag.BToD2),
ConversionMethod.D3 => toPcs ?
InitD(profile, IccProfileTag.DToB3) :
InitD(profile, IccProfileTag.BToD3),
ConversionMethod.A0 => toPcs ?
InitA(profile, IccProfileTag.AToB0) :
InitA(profile, IccProfileTag.BToA0),
ConversionMethod.A1 => toPcs ?
InitA(profile, IccProfileTag.AToB1) :
InitA(profile, IccProfileTag.BToA1),
ConversionMethod.A2 => toPcs ?
InitA(profile, IccProfileTag.AToB2) :
InitA(profile, IccProfileTag.BToA2),
ConversionMethod.ColorTrc => InitColorTrc(profile, toPcs),
ConversionMethod.GrayTrc => InitGrayTrc(profile, toPcs),
_ => throw new InvalidIccProfileException("Invalid conversion method."),
};
private static IVector4Calculator InitA(IccProfile profile, IccProfileTag tag)
=> GetTag(profile, tag) switch
{
IccLut8TagDataEntry lut8 => new LutEntryCalculator(lut8),
IccLut16TagDataEntry lut16 => new LutEntryCalculator(lut16),
IccLutAToBTagDataEntry lutAtoB => new LutABCalculator(lutAtoB),
IccLutBToATagDataEntry lutBtoA => new LutABCalculator(lutBtoA),
_ => throw new InvalidIccProfileException("Invalid entry."),
};
private static IVector4Calculator InitD(IccProfile profile, IccProfileTag tag)
{
IccMultiProcessElementsTagDataEntry entry = GetTag<IccMultiProcessElementsTagDataEntry>(profile, tag)
?? throw new InvalidIccProfileException("Entry is null.");
throw new NotImplementedException("Multi process elements are not supported");
}
private static ColorTrcCalculator InitColorTrc(IccProfile profile, bool toPcs)
{
IccXyzTagDataEntry redMatrixColumn = GetTag<IccXyzTagDataEntry>(profile, IccProfileTag.RedMatrixColumn);
IccXyzTagDataEntry greenMatrixColumn = GetTag<IccXyzTagDataEntry>(profile, IccProfileTag.GreenMatrixColumn);
IccXyzTagDataEntry blueMatrixColumn = GetTag<IccXyzTagDataEntry>(profile, IccProfileTag.BlueMatrixColumn);
IccTagDataEntry redTrc = GetTag(profile, IccProfileTag.RedTrc);
IccTagDataEntry greenTrc = GetTag(profile, IccProfileTag.GreenTrc);
IccTagDataEntry blueTrc = GetTag(profile, IccProfileTag.BlueTrc);
if (redMatrixColumn == null ||
greenMatrixColumn == null ||
blueMatrixColumn == null ||
redTrc == null ||
greenTrc == null ||
blueTrc == null)
{
throw new InvalidIccProfileException("Missing matrix column or channel.");
}
return new ColorTrcCalculator(
redMatrixColumn,
greenMatrixColumn,
blueMatrixColumn,
redTrc,
greenTrc,
blueTrc,
toPcs);
}
private static GrayTrcCalculator InitGrayTrc(IccProfile profile, bool toPcs)
{
IccTagDataEntry entry = GetTag(profile, IccProfileTag.GrayTrc);
return new GrayTrcCalculator(entry, toPcs);
}
}

49
src/ImageSharp/ColorProfiles/Icc/IccConverterbase.cs

@ -0,0 +1,49 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using System.Numerics;
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal abstract partial class IccConverterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IccConverterBase"/> class.
/// </summary>
/// <param name="profile">The ICC profile to use for the conversions</param>
/// <param name="toPcs">True if the conversion is to the profile connection space (PCS); False if the conversion is to the data space</param>
protected IccConverterBase(IccProfile profile, bool toPcs)
{
Guard.NotNull(profile, nameof(profile));
this.Init(profile, toPcs, profile.Header.RenderingIntent);
}
/// <summary>
/// Converts colors with the initially provided ICC profile
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>The converted value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 Calculate(Vector4 value) => this.calculator.Calculate(value);
/// <summary>
/// Converts colors with the initially provided ICC profile
/// </summary>
/// <param name="source">The source colors</param>
/// <param name="destination">The destination colors</param>
public void Calculate(ReadOnlySpan<Vector4> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
for (int i = 0; i < source.Length; i++)
{
destination[i] = this.Calculate(source[i]);
}
}
}

22
src/ImageSharp/ColorProfiles/Icc/IccDataToDataConverter.cs

@ -0,0 +1,22 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal class IccDataToDataConverter : IccConverterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IccDataToDataConverter"/> class.
/// </summary>
/// <param name="profile">The ICC profile to use for the conversions</param>
public IccDataToDataConverter(IccProfile profile)
: base(profile, true) // toPCS is true because in this case the PCS space is also a data space
{
}
}

22
src/ImageSharp/ColorProfiles/Icc/IccDataToPcsConverter.cs

@ -0,0 +1,22 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal class IccDataToPcsConverter : IccConverterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IccDataToPcsConverter"/> class.
/// </summary>
/// <param name="profile">The ICC profile to use for the conversions</param>
public IccDataToPcsConverter(IccProfile profile)
: base(profile, true)
{
}
}

22
src/ImageSharp/ColorProfiles/Icc/IccPcsToDataConverter.cs

@ -0,0 +1,22 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal class IccPcsToDataConverter : IccConverterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IccPcsToDataConverter"/> class.
/// </summary>
/// <param name="profile">The ICC profile to use for the conversions</param>
public IccPcsToDataConverter(IccProfile profile)
: base(profile, false)
{
}
}

22
src/ImageSharp/ColorProfiles/Icc/IccPcsToPcsConverter.cs

@ -0,0 +1,22 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Icc;
/// <summary>
/// Color converter for ICC profiles
/// </summary>
internal class IccPcsToPcsConverter : IccConverterBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IccPcsToPcsConverter"/> class.
/// </summary>
/// <param name="profile">The ICC profile to use for the conversions</param>
public IccPcsToPcsConverter(IccProfile profile)
: base(profile, true)
{
}
}

45
src/ImageSharp/ColorProfiles/Icc/SrgbV4Profile.Generated.cs

@ -0,0 +1,45 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
// <auto-generated />
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.ColorProfiles.Conversion.Icc;
internal static class SrgbV4Profile
{
// Generated using the sRGB-v4.icc profile found at https://github.com/saucecontrol/Compact-ICC-Profiles
private static ReadOnlySpan<byte> Data => new byte[]
{
0, 0, 1, 224, 108, 99, 109, 115, 4, 32, 0, 0, 109, 110, 116, 114, 82, 71, 66, 32, 88, 89, 90, 32, 7, 226, 0, 3, 0,
20, 0, 9, 0, 14, 0, 29, 97, 99, 115, 112, 77, 83, 70, 84, 0, 0, 0, 0, 115, 97, 119, 115, 99, 116, 114, 108, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 246, 214, 0, 1, 0, 0, 0, 0, 211, 45, 104, 97, 110, 100, 163, 178, 171,
223, 92, 167, 3, 18, 168, 85, 164, 236, 53, 122, 209, 243, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 100, 101, 115, 99, 0, 0, 0, 252, 0, 0, 0, 36, 99,
112, 114, 116, 0, 0, 1, 32, 0, 0, 0, 34, 119, 116, 112, 116, 0, 0, 1, 68, 0, 0, 0, 20, 99, 104, 97, 100, 0, 0,
1, 88, 0, 0, 0, 44, 114, 88, 89, 90, 0, 0, 1, 132, 0, 0, 0, 20, 103, 88, 89, 90, 0, 0, 1, 152, 0, 0, 0,
20, 98, 88, 89, 90, 0, 0, 1, 172, 0, 0, 0, 20, 114, 84, 82, 67, 0, 0, 1, 192, 0, 0, 0, 32, 103, 84, 82, 67,
0, 0, 1, 192, 0, 0, 0, 32, 98, 84, 82, 67, 0, 0, 1, 192, 0, 0, 0, 32, 109, 108, 117, 99, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 12, 101, 110, 85, 83, 0, 0, 0, 8, 0, 0, 0, 28, 0, 115, 0, 82, 0, 71, 0, 66, 109, 108,
117, 99, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 101, 110, 85, 83, 0, 0, 0, 6, 0, 0, 0, 28, 0, 67, 0,
67, 0, 48, 0, 33, 88, 89, 90, 32, 0, 0, 0, 0, 0, 0, 246, 214, 0, 1, 0, 0, 0, 0, 211, 45, 115, 102, 51, 50,
0, 0, 0, 0, 0, 1, 12, 63, 0, 0, 5, 221, 255, 255, 243, 38, 0, 0, 7, 144, 0, 0, 253, 146, 255, 255, 251, 161, 255,
255, 253, 162, 0, 0, 3, 220, 0, 0, 192, 113, 88, 89, 90, 32, 0, 0, 0, 0, 0, 0, 111, 160, 0, 0, 56, 242, 0, 0,
3, 143, 88, 89, 90, 32, 0, 0, 0, 0, 0, 0, 98, 150, 0, 0, 183, 137, 0, 0, 24, 218, 88, 89, 90, 32, 0, 0, 0,
0, 0, 0, 36, 160, 0, 0, 15, 133, 0, 0, 182, 196, 112, 97, 114, 97, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 102, 105,
0, 0, 242, 167, 0, 0, 13, 89, 0, 0, 19, 208, 0, 0, 10, 91,
};
private static readonly Lazy<IccProfile> LazyIccProfile = new(() => GetIccProfile());
public static IccProfile GetProfile() => LazyIccProfile.Value;
private static IccProfile GetIccProfile()
{
byte[] buffer = new byte[Data.Length];
Data.CopyTo(buffer);
return new IccProfile(buffer);
}
}

62
src/ImageSharp/ColorProfiles/KnownYCbCrMatrices.cs

@ -0,0 +1,62 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// Provides standard YCbCr matrices for RGB to YCbCr conversion.
/// </summary>
public static class KnownYCbCrMatrices
{
#pragma warning disable SA1137 // Elements should have the same indentation
#pragma warning disable SA1117 // Parameters should be on same line or separate lines
/// <summary>
/// ITU-R BT.601 (SD video standard).
/// </summary>
public static readonly YCbCrMatrix BT601 = new(
new Matrix4x4(
0.299000F, 0.587000F, 0.114000F, 0F,
-0.168736F, -0.331264F, 0.500000F, 0F,
0.500000F, -0.418688F, -0.081312F, 0F,
0F, 0F, 0F, 1F),
new Matrix4x4(
1.000000F, 0.000000F, 1.402000F, 0F,
1.000000F, -0.344136F, -0.714136F, 0F,
1.000000F, 1.772000F, 0.000000F, 0F,
0F, 0F, 0F, 1F),
new Vector3(0F, 0.5F, 0.5F));
/// <summary>
/// ITU-R BT.709 (HD video, sRGB standard).
/// </summary>
public static readonly YCbCrMatrix BT709 = new(
new Matrix4x4(
0.212600F, 0.715200F, 0.072200F, 0F,
-0.114572F, -0.385428F, 0.500000F, 0F,
0.500000F, -0.454153F, -0.045847F, 0F,
0F, 0F, 0F, 1F),
new Matrix4x4(
1.000000F, 0.000000F, 1.574800F, 0F,
1.000000F, -0.187324F, -0.468124F, 0F,
1.000000F, 1.855600F, 0.000000F, 0F,
0F, 0F, 0F, 1F),
new Vector3(0F, 0.5F, 0.5F));
/// <summary>
/// ITU-R BT.2020 (UHD/4K video standard).
/// </summary>
public static readonly YCbCrMatrix BT2020 = new(
new Matrix4x4(
0.262700F, 0.678000F, 0.059300F, 0F,
-0.139630F, -0.360370F, 0.500000F, 0F,
0.500000F, -0.459786F, -0.040214F, 0F,
0F, 0F, 0F, 1F),
new Matrix4x4(
1.000000F, 0.000000F, 1.474600F, 0F,
1.000000F, -0.164553F, -0.571353F, 0F,
1.000000F, 1.881400F, 0.000000F, 0F,
0F, 0F, 0F, 1F),
new Vector3(0F, 0.5F, 0.5F));
}

56
src/ImageSharp/ColorProfiles/Lms.cs

@ -82,20 +82,53 @@ public readonly struct Lms : IColorProfile<Lms, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Lms left, Lms right) => !left.Equals(right);
/// <summary>
/// Returns a new <see cref="Vector3"/> representing this instance.
/// </summary>
/// <returns>The <see cref="Vector3"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 ToVector3() => new(this.L, this.M, this.S);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
v3 += new Vector3(1F);
v3 /= 2F;
return new Vector4(v3, 1F);
}
/// <inheritdoc/>
public static Lms FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
public static Lms FromScaledVector4(Vector4 source)
{
Vector3 v3 = source.AsVector3();
v3 *= 2F;
v3 -= new Vector3(1F);
return new Lms(v3);
}
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Lms> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Lms> destination)
{
Vector3 vector = Vector3.Transform(source.ToVector3(), options.AdaptationMatrix);
return new Lms(vector);
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static Lms FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
=> new(Vector3.Transform(source.AsVector3Unsafe(), options.AdaptationMatrix));
/// <inheritdoc/>
public static void FromProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<CieXyz> source, Span<Lms> destination)
{
@ -110,10 +143,7 @@ public readonly struct Lms : IColorProfile<Lms, CieXyz>
/// <inheritdoc/>
public CieXyz ToProfileConnectingSpace(ColorConversionOptions options)
{
Vector3 vector = Vector3.Transform(this.ToVector3(), options.InverseAdaptationMatrix);
return new CieXyz(vector);
}
=> new(Vector3.Transform(this.AsVector3Unsafe(), options.InverseAdaptationMatrix));
/// <inheritdoc/>
public static void ToProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<Lms> source, Span<CieXyz> destination)

104
src/ImageSharp/ColorProfiles/Rgb.cs

@ -81,11 +81,54 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Rgb left, Rgb right) => !left.Equals(right);
/// <summary>
/// Initializes the color instance from a generic scaled <see cref="Vector4"/>.
/// </summary>
/// <param name="source">The vector to load the color from.</param>
/// <returns>The <see cref="Rgb"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rgb FromScaledVector4(Vector4 source)
=> new(source.AsVector3());
/// <summary>
/// Expands the color into a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and usually clamped between <value>0</value> and <value>1</value>.
/// The vector components are typically expanded in least to greatest significance order.
/// </summary>
/// <returns>The <see cref="Vector4"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 ToScaledVector4()
=> new(this.ToScaledVector3(), 1F);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Rgb> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Rgb> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static Rgb FromProfileConnectingSpace(ColorConversionOptions options, in CieXyz source)
{
// Convert to linear rgb then compress.
Rgb linear = new(Vector3.Transform(source.ToVector3(), GetCieXyzToRgbMatrix(options.TargetRgbWorkingSpace)));
Rgb linear = new(Vector3.Transform(source.AsVector3Unsafe(), GetCieXyzToRgbMatrix(options.TargetRgbWorkingSpace)));
return FromScaledVector4(options.TargetRgbWorkingSpace.Compress(linear.ToScaledVector4()));
}
@ -98,7 +141,7 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
for (int i = 0; i < source.Length; i++)
{
// Convert to linear rgb then compress.
Rgb linear = new(Vector3.Transform(source[i].ToVector3(), matrix));
Rgb linear = new(Vector3.Transform(source[i].AsVector3Unsafe(), matrix));
Vector4 nonlinear = options.TargetRgbWorkingSpace.Compress(linear.ToScaledVector4());
destination[i] = FromScaledVector4(nonlinear);
}
@ -108,10 +151,10 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
public CieXyz ToProfileConnectingSpace(ColorConversionOptions options)
{
// First expand to linear rgb
Rgb linear = FromScaledVector4(options.RgbWorkingSpace.Expand(this.ToScaledVector4()));
Rgb linear = FromScaledVector4(options.SourceRgbWorkingSpace.Expand(this.ToScaledVector4()));
// Then convert to xyz
return new CieXyz(Vector3.Transform(linear.ToScaledVector3(), GetRgbToCieXyzMatrix(options.RgbWorkingSpace)));
return new CieXyz(Vector3.Transform(linear.ToScaledVector3(), GetRgbToCieXyzMatrix(options.SourceRgbWorkingSpace)));
}
/// <inheritdoc/>
@ -119,13 +162,13 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
Matrix4x4 matrix = GetRgbToCieXyzMatrix(options.RgbWorkingSpace);
Matrix4x4 matrix = GetRgbToCieXyzMatrix(options.SourceRgbWorkingSpace);
for (int i = 0; i < source.Length; i++)
{
Rgb rgb = source[i];
// First expand to linear rgb
Rgb linear = FromScaledVector4(options.RgbWorkingSpace.Expand(rgb.ToScaledVector4()));
Rgb linear = FromScaledVector4(options.SourceRgbWorkingSpace.Expand(rgb.ToScaledVector4()));
// Then convert to xyz
destination[i] = new CieXyz(Vector3.Transform(linear.ToScaledVector3(), matrix));
@ -133,7 +176,8 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
}
/// <inheritdoc/>
public static ChromaticAdaptionWhitePointSource GetChromaticAdaptionWhitePointSource() => ChromaticAdaptionWhitePointSource.RgbWorkingSpace;
public static ChromaticAdaptionWhitePointSource GetChromaticAdaptionWhitePointSource()
=> ChromaticAdaptionWhitePointSource.RgbWorkingSpace;
/// <summary>
/// Initializes the color instance from a generic scaled <see cref="Vector3"/>.
@ -141,19 +185,8 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
/// <param name="source">The vector to load the color from.</param>
/// <returns>The <see cref="Rgb"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rgb FromScaledVector3(Vector3 source) => new(Vector3.Clamp(source, Vector3.Zero, Vector3.One));
/// <summary>
/// Initializes the color instance from a generic scaled <see cref="Vector4"/>.
/// </summary>
/// <param name="source">The vector to load the color from.</param>
/// <returns>The <see cref="Rgb"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rgb FromScaledVector4(Vector4 source)
{
source = Vector4.Clamp(source, Vector4.Zero, Vector4.One);
return new(source.X, source.Y, source.Z);
}
public static Rgb FromScaledVector3(Vector3 source)
=> new(source);
/// <summary>
/// Initializes the color instance for a source clamped between <value>0</value> and <value>1</value>
@ -161,7 +194,8 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
/// <param name="source">The source to load the color from.</param>
/// <returns>The <see cref="Rgb"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rgb Clamp(Rgb source) => new(Vector3.Clamp(new(source.R, source.G, source.B), Vector3.Zero, Vector3.One));
public static Rgb Clamp(Rgb source)
=> new(Vector3.Clamp(source.AsVector3Unsafe(), Vector3.Zero, Vector3.One));
/// <summary>
/// Expands the color into a generic ("scaled") <see cref="Vector3"/> representation
@ -170,24 +204,12 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
/// </summary>
/// <returns>The <see cref="Vector3"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 ToScaledVector3() => Clamp(this).ToVector3();
/// <summary>
/// Expands the color into a generic <see cref="Vector3"/> representation.
/// The vector components are typically expanded in least to greatest significance order.
/// </summary>
/// <returns>The <see cref="Vector3"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 ToVector3() => new(this.R, this.G, this.B);
/// <summary>
/// Expands the color into a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and usually clamped between <value>0</value> and <value>1</value>.
/// The vector components are typically expanded in least to greatest significance order.
/// </summary>
/// <returns>The <see cref="Vector4"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 ToScaledVector4() => new(this.ToScaledVector3(), 1f);
public Vector3 ToScaledVector3()
{
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
return v3;
}
/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(this.R, this.G, this.B);
@ -203,7 +225,7 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
public bool Equals(Rgb other)
=> this.AsVector3Unsafe() == other.AsVector3Unsafe();
private Vector3 AsVector3Unsafe() => Unsafe.As<Rgb, Vector3>(ref Unsafe.AsRef(in this));
internal Vector3 AsVector3Unsafe() => Unsafe.As<Rgb, Vector3>(ref Unsafe.AsRef(in this));
private static Matrix4x4 GetCieXyzToRgbMatrix(RgbWorkingSpace workingSpace)
{
@ -249,7 +271,7 @@ public readonly struct Rgb : IProfileConnectingSpace<Rgb, CieXyz>
Matrix4x4.Invert(xyzMatrix, out Matrix4x4 inverseXyzMatrix);
Vector3 vector = Vector3.Transform(workingSpace.WhitePoint.ToVector3(), inverseXyzMatrix);
Vector3 vector = Vector3.Transform(workingSpace.WhitePoint.AsVector3Unsafe(), inverseXyzMatrix);
// Use transposed Rows/Columns
return new Matrix4x4

12
src/ImageSharp/ColorProfiles/VonKriesChromaticAdaptation.cs

@ -34,9 +34,9 @@ public static class VonKriesChromaticAdaptation
return new(source.X, source.Y, source.Z);
}
Vector3 sourceColorLms = Vector3.Transform(source.ToVector3(), matrix);
Vector3 sourceWhitePointLms = Vector3.Transform(from.ToVector3(), matrix);
Vector3 targetWhitePointLms = Vector3.Transform(to.ToVector3(), matrix);
Vector3 sourceColorLms = Vector3.Transform(source.AsVector3Unsafe(), matrix);
Vector3 sourceWhitePointLms = Vector3.Transform(from.AsVector3Unsafe(), matrix);
Vector3 targetWhitePointLms = Vector3.Transform(to.AsVector3Unsafe(), matrix);
Vector3 vector = targetWhitePointLms / sourceWhitePointLms;
Vector3 targetColorLms = Vector3.Multiply(vector, sourceColorLms);
@ -76,8 +76,8 @@ public static class VonKriesChromaticAdaptation
ref CieXyz sourceBase = ref MemoryMarshal.GetReference(source);
ref CieXyz destinationBase = ref MemoryMarshal.GetReference(destination);
Vector3 sourceWhitePointLms = Vector3.Transform(from.ToVector3(), matrix);
Vector3 targetWhitePointLms = Vector3.Transform(to.ToVector3(), matrix);
Vector3 sourceWhitePointLms = Vector3.Transform(from.AsVector3Unsafe(), matrix);
Vector3 targetWhitePointLms = Vector3.Transform(to.AsVector3Unsafe(), matrix);
Vector3 vector = targetWhitePointLms / sourceWhitePointLms;
@ -86,7 +86,7 @@ public static class VonKriesChromaticAdaptation
ref CieXyz sp = ref Unsafe.Add(ref sourceBase, i);
ref CieXyz dp = ref Unsafe.Add(ref destinationBase, i);
Vector3 sourceColorLms = Vector3.Transform(sp.ToVector3(), matrix);
Vector3 sourceColorLms = Vector3.Transform(sp.AsVector3Unsafe(), matrix);
Vector3 targetColorLms = Vector3.Multiply(vector, sourceColorLms);
dp = new CieXyz(Vector3.Transform(targetColorLms, inverseMatrix));

142
src/ImageSharp/ColorProfiles/Y.cs

@ -0,0 +1,142 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// Represents a Y (luminance) color.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct Y : IColorProfile<Y, Rgb>
{
/// <summary>
/// Initializes a new instance of the <see cref="Y"/> struct.
/// </summary>
/// <param name="l">The luminance component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Y(float l) => this.L = Numerics.Clamp(l, 0, 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private Y(float l, bool _) => this.L = l;
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
/// <summary>
/// Gets the luminance component.
/// </summary>
/// <remarks>A value ranging between 0 and 1.</remarks>
public float L { get; }
/// <summary>
/// Compares two <see cref="Y"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Y"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Y"/> on the right side of the operand.</param>
/// <returns>
/// True if the current left is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Y left, Y right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Y"/> objects for inequality.
/// </summary>
/// <param name="left">The <see cref="Y"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Y"/> on the right side of the operand.</param>
/// <returns>
/// True if the current left is unequal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Y left, Y right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4() => new(this.L);
/// <inheritdoc/>
public static Y FromScaledVector4(Vector4 source) => new(source.X, true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<Y> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<Y> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public Rgb ToProfileConnectingSpace(ColorConversionOptions options)
=> new(this.L, this.L, this.L);
/// <inheritdoc/>
public static Y FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{
Matrix4x4 m = options.YCbCrMatrix.Forward;
float offset = options.YCbCrMatrix.Offset.X;
return new(Vector3.Dot(source.AsVector3Unsafe(), new Vector3(m.M11, m.M12, m.M13)) + offset);
}
/// <inheritdoc/>
public static void ToProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<Y> source, Span<Rgb> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: We can optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToProfileConnectingSpace(options);
}
}
/// <inheritdoc/>
public static void FromProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<Rgb> source, Span<Y> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: We can optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
Rgb rgb = source[i];
destination[i] = FromProfileConnectingSpace(options, in rgb);
}
}
/// <inheritdoc/>
public static ChromaticAdaptionWhitePointSource GetChromaticAdaptionWhitePointSource()
=> ChromaticAdaptionWhitePointSource.RgbWorkingSpace;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
=> this.L.GetHashCode();
/// <inheritdoc/>
public override string ToString()
=> FormattableString.Invariant($"Y({this.L:#0.##})");
/// <inheritdoc/>
public override bool Equals(object? obj)
=> obj is Y other && this.Equals(other);
/// <inheritdoc/>
public bool Equals(Y other) => this.L == other.L;
}

86
src/ImageSharp/ColorProfiles/YCbCr.cs

@ -8,15 +8,13 @@ using System.Runtime.InteropServices;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// Represents an YCbCr (luminance, blue chroma, red chroma) color as defined in the ITU-T T.871 specification for the JFIF use with Jpeg.
/// <see href="http://en.wikipedia.org/wiki/YCbCr"/>
/// <see href="http://www.ijg.org/files/T-REC-T.871-201105-I!!PDF-E.pdf"/>
/// Represents an YCbCr (luminance, blue chroma, red chroma) color.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct YCbCr : IColorProfile<YCbCr, Rgb>
{
private static readonly Vector3 Min = Vector3.Zero;
private static readonly Vector3 Max = new(255);
private static readonly Vector3 Max = Vector3.One;
/// <summary>
/// Initializes a new instance of the <see cref="YCbCr"/> struct.
@ -43,21 +41,31 @@ public readonly struct YCbCr : IColorProfile<YCbCr, Rgb>
this.Cr = vector.Z;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private YCbCr(Vector3 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.Y = vector.X;
this.Cb = vector.Y;
this.Cr = vector.Z;
}
/// <summary>
/// Gets the Y luminance component.
/// <remarks>A value ranging between 0 and 255.</remarks>
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Y { get; }
/// <summary>
/// Gets the Cb chroma component.
/// <remarks>A value ranging between 0 and 255.</remarks>
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Cb { get; }
/// <summary>
/// Gets the Cr chroma component.
/// <remarks>A value ranging between 0 and 255.</remarks>
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Cr { get; }
@ -83,18 +91,49 @@ public readonly struct YCbCr : IColorProfile<YCbCr, Rgb>
public static bool operator !=(YCbCr left, YCbCr right) => !left.Equals(right);
/// <inheritdoc/>
public static YCbCr FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
public Vector4 ToScaledVector4()
{
Vector3 rgb = source.ToScaledVector3() * Max;
float r = rgb.X;
float g = rgb.Y;
float b = rgb.Z;
Vector3 v3 = default;
v3 += this.AsVector3Unsafe();
return new Vector4(v3, 1F);
}
float y = (0.299F * r) + (0.587F * g) + (0.114F * b);
float cb = 128F + ((-0.168736F * r) - (0.331264F * g) + (0.5F * b));
float cr = 128F + ((0.5F * r) - (0.418688F * g) - (0.081312F * b));
/// <inheritdoc/>
public static YCbCr FromScaledVector4(Vector4 source)
=> new(source.AsVector3(), true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<YCbCr> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
return new YCbCr(y, cb, cr);
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToScaledVector4();
}
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<YCbCr> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: Optimize via SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = FromScaledVector4(source[i]);
}
}
/// <inheritdoc/>
public static YCbCr FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{
Vector3 rgb = source.AsVector3Unsafe();
Matrix4x4 m = options.TransposedYCbCrMatrix.Forward;
Vector3 offset = options.TransposedYCbCrMatrix.Offset;
return new YCbCr(Vector3.Transform(rgb, m) + offset, true);
}
/// <inheritdoc/>
@ -113,15 +152,11 @@ public readonly struct YCbCr : IColorProfile<YCbCr, Rgb>
/// <inheritdoc/>
public Rgb ToProfileConnectingSpace(ColorConversionOptions options)
{
float y = this.Y;
float cb = this.Cb - 128F;
float cr = this.Cr - 128F;
float r = MathF.Round(y + (1.402F * cr), MidpointRounding.AwayFromZero);
float g = MathF.Round(y - (0.344136F * cb) - (0.714136F * cr), MidpointRounding.AwayFromZero);
float b = MathF.Round(y + (1.772F * cb), MidpointRounding.AwayFromZero);
Matrix4x4 m = options.TransposedYCbCrMatrix.Inverse;
Vector3 offset = options.TransposedYCbCrMatrix.Offset;
Vector3 normalized = this.AsVector3Unsafe() - offset;
return Rgb.FromScaledVector3(new Vector3(r, g, b) / Max);
return Rgb.FromScaledVector3(Vector3.Transform(normalized, m));
}
/// <inheritdoc/>
@ -132,8 +167,7 @@ public readonly struct YCbCr : IColorProfile<YCbCr, Rgb>
// TODO: We can optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
YCbCr ycbcr = source[i];
destination[i] = ycbcr.ToProfileConnectingSpace(options);
destination[i] = source[i].ToProfileConnectingSpace(options);
}
}

61
src/ImageSharp/ColorProfiles/YcbCrMatrix.cs

@ -0,0 +1,61 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using SixLabors.ImageSharp.ColorProfiles.WorkingSpaces;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// <para>
/// Represents a YCbCr color matrix containing forward and inverse transformation matrices,
/// and the chrominance offsets to apply for full-range encoding
/// </para>
/// <para>
/// These matrices must be selected to match the characteristics of the associated <see cref="RgbWorkingSpace"/>,
/// including its transfer function (gamma or companding) and chromaticity coordinates. Using mismatched matrices and
/// working spaces will produce incorrect conversions.
/// </para>
/// </summary>
public readonly struct YCbCrMatrix
{
/// <summary>
/// Initializes a new instance of the <see cref="YCbCrMatrix"/> struct.
/// </summary>
/// <param name="forward">
/// The forward transformation matrix from RGB to YCbCr. The matrix must include the
/// standard chrominance offsets in the fourth column, such as <c>(0, 0.5, 0.5)</c>.
/// </param>
/// <param name="inverse">
/// The inverse transformation matrix from YCbCr to RGB. This matrix expects that
/// chrominance offsets have already been subtracted prior to application.
/// </param>
/// <param name="offset">
/// The chrominance offsets to be added after the forward conversion,
/// and subtracted before the inverse conversion. Usually <c>(0, 0.5, 0.5)</c>.
/// </param>
public YCbCrMatrix(Matrix4x4 forward, Matrix4x4 inverse, Vector3 offset)
{
this.Forward = forward;
this.Inverse = inverse;
this.Offset = offset;
}
/// <summary>
/// Gets the matrix used to convert gamma-encoded RGB to YCbCr.
/// </summary>
public Matrix4x4 Forward { get; }
/// <summary>
/// Gets the matrix used to convert YCbCr back to gamma-encoded RGB.
/// </summary>
public Matrix4x4 Inverse { get; }
/// <summary>
/// Gets the chrominance offset vector to apply during encoding (add) or decoding (subtract).
/// </summary>
public Vector3 Offset { get; }
internal YCbCrMatrix Transpose()
=> new(Matrix4x4.Transpose(this.Forward), Matrix4x4.Transpose(this.Inverse), this.Offset);
}

206
src/ImageSharp/ColorProfiles/YccK.cs

@ -0,0 +1,206 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace SixLabors.ImageSharp.ColorProfiles;
/// <summary>
/// Represents a YCCK (luminance, blue chroma, red chroma, black) color.
/// YCCK is not a true color space but a reversible transform of CMYK, where the CMY components
/// are converted to YCbCr using the ITU-R BT.601 standard, and the K (black) component is preserved separately.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct YccK : IColorProfile<YccK, Rgb>
{
private static readonly Vector4 Min = Vector4.Zero;
private static readonly Vector4 Max = Vector4.One;
/// <summary>
/// Initializes a new instance of the <see cref="YccK"/> struct.
/// </summary>
/// <param name="y">The y luminance component.</param>
/// <param name="cb">The cb chroma component.</param>
/// <param name="cr">The cr chroma component.</param>
/// <param name="k">The keyline black component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public YccK(float y, float cb, float cr, float k)
: this(new Vector4(y, cb, cr, k))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YccK"/> struct.
/// </summary>
/// <param name="vector">The vector representing the c, m, y, k components.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public YccK(Vector4 vector)
{
vector = Vector4.Clamp(vector, Min, Max);
this.Y = vector.X;
this.Cb = vector.Y;
this.Cr = vector.Z;
this.K = vector.W;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private YccK(Vector4 vector, bool _)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
this.Y = vector.X;
this.Cb = vector.Y;
this.Cr = vector.Z;
this.K = vector.W;
}
/// <summary>
/// Gets the Y luminance component.
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Y { get; }
/// <summary>
/// Gets the C (blue) chroma component.
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Cb { get; }
/// <summary>
/// Gets the C (red) chroma component.
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float Cr { get; }
/// <summary>
/// Gets the keyline black color component.
/// <remarks>A value ranging between 0 and 1.</remarks>
/// </summary>
public float K { get; }
/// <summary>
/// Compares two <see cref="YccK"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="YccK"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="YccK"/> on the right side of the operand.</param>
/// <returns>
/// True if the current left is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(YccK left, YccK right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="YccK"/> objects for inequality.
/// </summary>
/// <param name="left">The <see cref="YccK"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="YccK"/> on the right side of the operand.</param>
/// <returns>
/// True if the current left is unequal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(YccK left, YccK right) => !left.Equals(right);
/// <inheritdoc/>
public Vector4 ToScaledVector4()
{
Vector4 v4 = default;
v4 += this.AsVector4Unsafe();
return v4;
}
/// <inheritdoc/>
public static YccK FromScaledVector4(Vector4 source)
=> new(source, true);
/// <inheritdoc/>
public static void ToScaledVector4(ReadOnlySpan<YccK> source, Span<Vector4> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
MemoryMarshal.Cast<YccK, Vector4>(source).CopyTo(destination);
}
/// <inheritdoc/>
public static void FromScaledVector4(ReadOnlySpan<Vector4> source, Span<YccK> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
MemoryMarshal.Cast<Vector4, YccK>(source).CopyTo(destination);
}
/// <inheritdoc/>
public Rgb ToProfileConnectingSpace(ColorConversionOptions options)
{
Matrix4x4 m = options.TransposedYCbCrMatrix.Inverse;
Vector3 offset = options.TransposedYCbCrMatrix.Offset;
Vector3 normalized = this.AsVector3Unsafe() - offset;
return Rgb.FromScaledVector3(Vector3.Transform(normalized, m) * (1F - this.K));
}
/// <inheritdoc/>
public static YccK FromProfileConnectingSpace(ColorConversionOptions options, in Rgb source)
{
Matrix4x4 m = options.TransposedYCbCrMatrix.Forward;
Vector3 offset = options.TransposedYCbCrMatrix.Offset;
Vector3 rgb = source.AsVector3Unsafe();
float k = 1F - MathF.Max(rgb.X, MathF.Max(rgb.Y, rgb.Z));
if (k >= 1F - Constants.Epsilon)
{
return new YccK(new Vector4(0F, 0.5F, 0.5F, 1F), true);
}
rgb /= 1F - k;
return new YccK(new Vector4(Vector3.Transform(rgb, m), k) + new Vector4(offset, 0F));
}
/// <inheritdoc/>
public static void ToProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<YccK> source, Span<Rgb> destination)
{
// TODO: We can possibly optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i].ToProfileConnectingSpace(options);
}
}
/// <inheritdoc/>
public static void FromProfileConnectionSpace(ColorConversionOptions options, ReadOnlySpan<Rgb> source, Span<YccK> destination)
{
Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination));
// TODO: We can optimize this by using SIMD
for (int i = 0; i < source.Length; i++)
{
Rgb rgb = source[i];
destination[i] = FromProfileConnectingSpace(options, in rgb);
}
}
/// <inheritdoc/>
public static ChromaticAdaptionWhitePointSource GetChromaticAdaptionWhitePointSource()
=> ChromaticAdaptionWhitePointSource.RgbWorkingSpace;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
=> HashCode.Combine(this.Y, this.Cb, this.Cr, this.K);
/// <inheritdoc/>
public override string ToString()
=> FormattableString.Invariant($"YccK({this.Y:#0.##}, {this.Cb:#0.##}, {this.Cr:#0.##}, {this.K:#0.##})");
/// <inheritdoc/>
public override bool Equals(object? obj)
=> obj is YccK other && this.Equals(other);
/// <inheritdoc/>
public bool Equals(YccK other)
=> this.AsVector4Unsafe() == other.AsVector4Unsafe();
private Vector3 AsVector3Unsafe() => Unsafe.As<YccK, Vector3>(ref Unsafe.AsRef(in this));
private Vector4 AsVector4Unsafe() => Unsafe.As<YccK, Vector4>(ref Unsafe.AsRef(in this));
}

21
src/ImageSharp/Common/Extensions/Vector4Extensions.cs

@ -0,0 +1,21 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#if !NET9_0_OR_GREATER
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace SixLabors.ImageSharp;
internal static class Vector4Extensions
{
/// <summary>
/// Reinterprets a <see cref="Vector4" /> as a new <see cref="Vector3" />.
/// </summary>
/// <param name="value">The vector to reinterpret.</param>
/// <returns><paramref name="value" /> reinterpreted as a new <see cref="Vector3" />.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 AsVector3(this Vector4 value) => value.AsVector128().AsVector3();
}
#endif

21
src/ImageSharp/Formats/ColorProfileHandling.cs

@ -0,0 +1,21 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Formats;
/// <summary>
/// Provides enumeration of methods that control how ICC profiles are handled during decode.
/// </summary>
public enum ColorProfileHandling
{
/// <summary>
/// Leaves any embedded ICC color profiles intact.
/// </summary>
Preserve,
/// <summary>
/// Transforms the pixels of the image based on the conversion of any embedded ICC color profiles to sRGB V4 profile.
/// The original profile is then replaced.
/// </summary>
Convert
}

6
src/ImageSharp/Formats/DecoderOptions.cs

@ -60,5 +60,11 @@ public sealed class DecoderOptions
/// </summary>
public SegmentIntegrityHandling SegmentIntegrityHandling { get; init; } = SegmentIntegrityHandling.IgnoreNonCritical;
/// <summary>
/// Gets a value that controls how ICC profiles are handled during decode.
/// TODO: Implement this.
/// </summary>
internal ColorProfileHandling ColorProfileHandling { get; init; }
internal void SetConfiguration(Configuration configuration) => this.configuration = configuration;
}

8
src/ImageSharp/Formats/ImageDecoder.cs

@ -46,10 +46,10 @@ public abstract class ImageDecoder : IImageDecoder
where TPixel : unmanaged, IPixel<TPixel>
{
Image<TPixel> image = await WithSeekableMemoryStreamAsync(
options,
stream,
(s, ct) => this.Decode<TPixel>(options, s, ct),
cancellationToken).ConfigureAwait(false);
options,
stream,
(s, ct) => this.Decode<TPixel>(options, s, ct),
cancellationToken).ConfigureAwait(false);
this.SetDecoderFormat(options.Configuration, image);

4
src/ImageSharp/Formats/SpecializedImageDecoder{T}.cs

@ -24,6 +24,7 @@ public abstract class SpecializedImageDecoder<T> : ImageDecoder, ISpecializedIma
s => this.Decode<TPixel>(options, s, default));
this.SetDecoderFormat(options.GeneralOptions.Configuration, image);
return image;
}
@ -36,6 +37,7 @@ public abstract class SpecializedImageDecoder<T> : ImageDecoder, ISpecializedIma
s => this.Decode(options, s, default));
this.SetDecoderFormat(options.GeneralOptions.Configuration, image);
return image;
}
@ -50,6 +52,7 @@ public abstract class SpecializedImageDecoder<T> : ImageDecoder, ISpecializedIma
cancellationToken).ConfigureAwait(false);
this.SetDecoderFormat(options.GeneralOptions.Configuration, image);
return image;
}
@ -63,6 +66,7 @@ public abstract class SpecializedImageDecoder<T> : ImageDecoder, ISpecializedIma
cancellationToken).ConfigureAwait(false);
this.SetDecoderFormat(options.GeneralOptions.Configuration, image);
return image;
}

85
src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Lut.cs

@ -4,24 +4,21 @@
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
/// <summary>
/// Provides methods to read ICC data types
/// Provides methods to read ICC data types.
/// </summary>
internal sealed partial class IccDataReader
{
/// <summary>
/// Reads an 8bit lookup table
/// Reads an 8bit lookup table.
/// </summary>
/// <returns>The read LUT</returns>
public IccLut ReadLut8()
{
return new IccLut(this.ReadBytes(256));
}
/// <returns>The read LUT.</returns>
public IccLut ReadLut8() => new(this.ReadBytes(256));
/// <summary>
/// Reads a 16bit lookup table
/// Reads a 16bit lookup table.
/// </summary>
/// <param name="count">The number of entries</param>
/// <returns>The read LUT</returns>
/// <param name="count">The number of entries.</param>
/// <returns>The read LUT.</returns>
public IccLut ReadLut16(int count)
{
var values = new ushort[count];
@ -34,16 +31,16 @@ internal sealed partial class IccDataReader
}
/// <summary>
/// Reads a CLUT depending on type
/// Reads a CLUT depending on type.
/// </summary>
/// <param name="inChannelCount">Input channel count</param>
/// <param name="outChannelCount">Output channel count</param>
/// <param name="inChannelCount">Input channel count.</param>
/// <param name="outChannelCount">Output channel count.</param>
/// <param name="isFloat">If true, it's read as CLUTf32,
/// else read as either CLUT8 or CLUT16 depending on embedded information</param>
/// <returns>The read CLUT</returns>
/// else read as either CLUT8 or CLUT16 depending on embedded information.</param>
/// <returns>The read CLUT.</returns>
public IccClut ReadClut(int inChannelCount, int outChannelCount, bool isFloat)
{
// Grid-points are always 16 bytes long but only 0-inChCount are used
// Grid-points are always 16 bytes long but only 0-inChCount are used.
var gridPointCount = new byte[inChannelCount];
Buffer.BlockCopy(this.data, this.AddIndex(16), gridPointCount, 0, inChannelCount);
@ -67,15 +64,14 @@ internal sealed partial class IccDataReader
}
/// <summary>
/// Reads an 8 bit CLUT
/// Reads an 8 bit CLUT.
/// </summary>
/// <param name="inChannelCount">Input channel count</param>
/// <param name="outChannelCount">Output channel count</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel</param>
/// <returns>The read CLUT8</returns>
/// <param name="inChannelCount">Input channel count.</param>
/// <param name="outChannelCount">Output channel count.</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel.</param>
/// <returns>The read CLUT8.</returns>
public IccClut ReadClut8(int inChannelCount, int outChannelCount, byte[] gridPointCount)
{
int start = this.currentIndex;
int length = 0;
for (int i = 0; i < inChannelCount; i++)
{
@ -86,27 +82,26 @@ internal sealed partial class IccDataReader
const float Max = byte.MaxValue;
var values = new float[length][];
float[] values = new float[length * outChannelCount];
int offset = 0;
for (int i = 0; i < length; i++)
{
values[i] = new float[outChannelCount];
for (int j = 0; j < outChannelCount; j++)
{
values[i][j] = this.data[this.currentIndex++] / Max;
values[offset++] = this.data[this.currentIndex++] / Max;
}
}
this.currentIndex = start + (length * outChannelCount);
return new IccClut(values, gridPointCount, IccClutDataType.UInt8);
return new IccClut(values, gridPointCount, IccClutDataType.UInt8, outChannelCount);
}
/// <summary>
/// Reads a 16 bit CLUT
/// Reads a 16 bit CLUT.
/// </summary>
/// <param name="inChannelCount">Input channel count</param>
/// <param name="outChannelCount">Output channel count</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel</param>
/// <returns>The read CLUT16</returns>
/// <param name="inChannelCount">Input channel count.</param>
/// <param name="outChannelCount">Output channel count.</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel.</param>
/// <returns>The read CLUT16.</returns>
public IccClut ReadClut16(int inChannelCount, int outChannelCount, byte[] gridPointCount)
{
int start = this.currentIndex;
@ -120,27 +115,27 @@ internal sealed partial class IccDataReader
const float Max = ushort.MaxValue;
var values = new float[length][];
float[] values = new float[length * outChannelCount];
int offset = 0;
for (int i = 0; i < length; i++)
{
values[i] = new float[outChannelCount];
for (int j = 0; j < outChannelCount; j++)
{
values[i][j] = this.ReadUInt16() / Max;
values[offset++] = this.ReadUInt16() / Max;
}
}
this.currentIndex = start + (length * outChannelCount * 2);
return new IccClut(values, gridPointCount, IccClutDataType.UInt16);
return new IccClut(values, gridPointCount, IccClutDataType.UInt16, outChannelCount);
}
/// <summary>
/// Reads a 32bit floating point CLUT
/// Reads a 32bit floating point CLUT.
/// </summary>
/// <param name="inChCount">Input channel count</param>
/// <param name="outChCount">Output channel count</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel</param>
/// <returns>The read CLUTf32</returns>
/// <param name="inChCount">Input channel count.</param>
/// <param name="outChCount">Output channel count.</param>
/// <param name="gridPointCount">Grid point count for each CLUT channel.</param>
/// <returns>The read CLUTf32.</returns>
public IccClut ReadClutF32(int inChCount, int outChCount, byte[] gridPointCount)
{
int start = this.currentIndex;
@ -152,17 +147,17 @@ internal sealed partial class IccDataReader
length /= inChCount;
var values = new float[length][];
float[] values = new float[length * outChCount];
int offset = 0;
for (int i = 0; i < length; i++)
{
values[i] = new float[outChCount];
for (int j = 0; j < outChCount; j++)
{
values[i][j] = this.ReadSingle();
values[offset++] = this.ReadSingle();
}
}
this.currentIndex = start + (length * outChCount * 4);
return new IccClut(values, gridPointCount, IccClutDataType.Float);
return new IccClut(values, gridPointCount, IccClutDataType.Float, outChCount);
}
}

28
src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Matrix.cs

@ -17,16 +17,23 @@ internal sealed partial class IccDataReader
/// <returns>The read matrix</returns>
public float[,] ReadMatrix(int xCount, int yCount, bool isSingle)
{
var matrix = new float[xCount, yCount];
for (int y = 0; y < yCount; y++)
float[,] matrix = new float[xCount, yCount];
if (isSingle)
{
for (int x = 0; x < xCount; x++)
for (int y = 0; y < yCount; y++)
{
if (isSingle)
for (int x = 0; x < xCount; x++)
{
matrix[x, y] = this.ReadSingle();
}
else
}
}
else
{
for (int y = 0; y < yCount; y++)
{
for (int x = 0; x < xCount; x++)
{
matrix[x, y] = this.ReadFix16();
}
@ -44,14 +51,17 @@ internal sealed partial class IccDataReader
/// <returns>The read matrix</returns>
public float[] ReadMatrix(int yCount, bool isSingle)
{
var matrix = new float[yCount];
for (int i = 0; i < yCount; i++)
float[] matrix = new float[yCount];
if (isSingle)
{
if (isSingle)
for (int i = 0; i < yCount; i++)
{
matrix[i] = this.ReadSingle();
}
else
}
else
{
for (int i = 0; i < yCount; i++)
{
matrix[i] = this.ReadFix16();
}

35
src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.Primitives.cs

@ -16,55 +16,37 @@ internal sealed partial class IccDataReader
/// Reads an ushort
/// </summary>
/// <returns>the value</returns>
public ushort ReadUInt16()
{
return BinaryPrimitives.ReadUInt16BigEndian(this.data.AsSpan(this.AddIndex(2), 2));
}
public ushort ReadUInt16() => BinaryPrimitives.ReadUInt16BigEndian(this.data.AsSpan(this.AddIndex(2), 2));
/// <summary>
/// Reads a short
/// </summary>
/// <returns>the value</returns>
public short ReadInt16()
{
return BinaryPrimitives.ReadInt16BigEndian(this.data.AsSpan(this.AddIndex(2), 2));
}
public short ReadInt16() => BinaryPrimitives.ReadInt16BigEndian(this.data.AsSpan(this.AddIndex(2), 2));
/// <summary>
/// Reads an uint
/// </summary>
/// <returns>the value</returns>
public uint ReadUInt32()
{
return BinaryPrimitives.ReadUInt32BigEndian(this.data.AsSpan(this.AddIndex(4), 4));
}
public uint ReadUInt32() => BinaryPrimitives.ReadUInt32BigEndian(this.data.AsSpan(this.AddIndex(4), 4));
/// <summary>
/// Reads an int
/// </summary>
/// <returns>the value</returns>
public int ReadInt32()
{
return BinaryPrimitives.ReadInt32BigEndian(this.data.AsSpan(this.AddIndex(4), 4));
}
public int ReadInt32() => BinaryPrimitives.ReadInt32BigEndian(this.data.AsSpan(this.AddIndex(4), 4));
/// <summary>
/// Reads an ulong
/// </summary>
/// <returns>the value</returns>
public ulong ReadUInt64()
{
return BinaryPrimitives.ReadUInt64BigEndian(this.data.AsSpan(this.AddIndex(8), 8));
}
public ulong ReadUInt64() => BinaryPrimitives.ReadUInt64BigEndian(this.data.AsSpan(this.AddIndex(8), 8));
/// <summary>
/// Reads a long
/// </summary>
/// <returns>the value</returns>
public long ReadInt64()
{
return BinaryPrimitives.ReadInt64BigEndian(this.data.AsSpan(this.AddIndex(8), 8));
}
public long ReadInt64() => BinaryPrimitives.ReadInt64BigEndian(this.data.AsSpan(this.AddIndex(8), 8));
/// <summary>
/// Reads a float.
@ -152,10 +134,7 @@ internal sealed partial class IccDataReader
/// Reads an unsigned 16bit number with 8 value bits and 8 fractional bits.
/// </summary>
/// <returns>The number as double</returns>
public float ReadUFix8()
{
return this.ReadUInt16() / 256f;
}
public float ReadUFix8() => this.ReadUInt16() / 256f;
/// <summary>
/// Reads a number of bytes and advances the index.

132
src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs

@ -8,21 +8,19 @@ using System.Numerics;
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
/// <summary>
/// Provides methods to read ICC data types
/// Provides methods to read ICC data types.
/// </summary>
internal sealed partial class IccDataReader
{
/// <summary>
/// Reads a tag data entry
/// Reads a tag data entry.
/// </summary>
/// <param name="info">The table entry with reading information</param>
/// <returns>the tag data entry</returns>
/// <param name="info">The table entry with reading information.</param>
/// <returns>The tag data entry.</returns>
public IccTagDataEntry ReadTagDataEntry(IccTagTableEntry info)
{
this.currentIndex = (int)info.Offset;
IccTypeSignature type = this.ReadTagDataEntryHeader();
switch (type)
switch (this.ReadTagDataEntryHeader())
{
case IccTypeSignature.Chromaticity:
return this.ReadChromaticityTagDataEntry();
@ -103,10 +101,10 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads the header of a <see cref="IccTagDataEntry"/>
/// </summary>
/// <returns>The read signature</returns>
/// <returns>The read signature.</returns>
public IccTypeSignature ReadTagDataEntryHeader()
{
var type = (IccTypeSignature)this.ReadUInt32();
IccTypeSignature type = (IccTypeSignature)this.ReadUInt32();
this.AddIndex(4); // 4 bytes are not used
return type;
}
@ -114,7 +112,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads the header of a <see cref="IccTagDataEntry"/> and checks if it's the expected value
/// </summary>
/// <param name="expected">expected value to check against</param>
/// <param name="expected">The expected value to check against.</param>
public void ReadCheckTagDataEntryHeader(IccTypeSignature expected)
{
IccTypeSignature type = this.ReadTagDataEntryHeader();
@ -127,8 +125,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccTagDataEntry"/> with an unknown <see cref="IccTypeSignature"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUnknownTagDataEntry ReadUnknownTagDataEntry(uint size)
{
int count = (int)size - 8; // 8 is the tag header size
@ -138,7 +136,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccChromaticityTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccChromaticityTagDataEntry ReadChromaticityTagDataEntry()
{
ushort channelCount = this.ReadUInt16();
@ -152,7 +150,7 @@ internal sealed partial class IccDataReader
}
else
{
// The type is not know, so the values need be read
// The type is not know, so the values need be read.
double[][] values = new double[channelCount][];
for (int i = 0; i < channelCount; i++)
{
@ -166,7 +164,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccColorantOrderTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccColorantOrderTagDataEntry ReadColorantOrderTagDataEntry()
{
uint colorantCount = this.ReadUInt32();
@ -177,7 +175,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccColorantTableTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccColorantTableTagDataEntry ReadColorantTableTagDataEntry()
{
uint colorantCount = this.ReadUInt32();
@ -193,7 +191,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccCurveTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccCurveTagDataEntry ReadCurveTagDataEntry()
{
uint pointCount = this.ReadUInt32();
@ -222,7 +220,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccDataTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry</returns>
public IccDataTagDataEntry ReadDataTagDataEntry(uint size)
{
@ -240,16 +238,13 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccDateTimeTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
public IccDateTimeTagDataEntry ReadDateTimeTagDataEntry()
{
return new IccDateTimeTagDataEntry(this.ReadDateTime());
}
/// <returns>The read entry.</returns>
public IccDateTimeTagDataEntry ReadDateTimeTagDataEntry() => new IccDateTimeTagDataEntry(this.ReadDateTime());
/// <summary>
/// Reads a <see cref="IccLut16TagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccLut16TagDataEntry ReadLut16TagDataEntry()
{
byte inChCount = this.data[this.AddIndex(1)];
@ -287,7 +282,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccLut8TagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccLut8TagDataEntry ReadLut8TagDataEntry()
{
byte inChCount = this.data[this.AddIndex(1)];
@ -322,7 +317,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccLutAToBTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccLutAToBTagDataEntry ReadLutAtoBTagDataEntry()
{
int start = this.currentIndex - 8; // 8 is the tag header size
@ -381,7 +376,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccLutBToATagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccLutBToATagDataEntry ReadLutBtoATagDataEntry()
{
int start = this.currentIndex - 8; // 8 is the tag header size
@ -440,21 +435,18 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccMeasurementTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
public IccMeasurementTagDataEntry ReadMeasurementTagDataEntry()
{
return new IccMeasurementTagDataEntry(
/// <returns>The read entry.</returns>
public IccMeasurementTagDataEntry ReadMeasurementTagDataEntry() => new(
observer: (IccStandardObserver)this.ReadUInt32(),
xyzBacking: this.ReadXyzNumber(),
geometry: (IccMeasurementGeometry)this.ReadUInt32(),
flare: this.ReadUFix16(),
illuminant: (IccStandardIlluminant)this.ReadUInt32());
}
/// <summary>
/// Reads a <see cref="IccMultiLocalizedUnicodeTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccMultiLocalizedUnicodeTagDataEntry ReadMultiLocalizedUnicodeTagDataEntry()
{
int start = this.currentIndex - 8; // 8 is the tag header size
@ -519,7 +511,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccMultiProcessElementsTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccMultiProcessElementsTagDataEntry ReadMultiProcessElementsTagDataEntry()
{
int start = this.currentIndex - 8;
@ -547,7 +539,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccNamedColor2TagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccNamedColor2TagDataEntry ReadNamedColor2TagDataEntry()
{
int vendorFlag = this.ReadInt32();
@ -569,15 +561,12 @@ internal sealed partial class IccDataReader
/// Reads a <see cref="IccParametricCurveTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
public IccParametricCurveTagDataEntry ReadParametricCurveTagDataEntry()
{
return new IccParametricCurveTagDataEntry(this.ReadParametricCurve());
}
public IccParametricCurveTagDataEntry ReadParametricCurveTagDataEntry() => new(this.ReadParametricCurve());
/// <summary>
/// Reads a <see cref="IccProfileSequenceDescTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccProfileSequenceDescTagDataEntry ReadProfileSequenceDescTagDataEntry()
{
uint count = this.ReadUInt32();
@ -593,7 +582,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccProfileSequenceIdentifierTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccProfileSequenceIdentifierTagDataEntry ReadProfileSequenceIdentifierTagDataEntry()
{
int start = this.currentIndex - 8; // 8 is the tag header size
@ -620,7 +609,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccResponseCurveSet16TagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccResponseCurveSet16TagDataEntry ReadResponseCurveSet16TagDataEntry()
{
int start = this.currentIndex - 8; // 8 is the tag header size
@ -646,8 +635,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccFix16ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccFix16ArrayTagDataEntry ReadFix16ArrayTagDataEntry(uint size)
{
uint count = (size - 8) / 4;
@ -663,27 +652,21 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccSignatureTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
public IccSignatureTagDataEntry ReadSignatureTagDataEntry()
{
return new IccSignatureTagDataEntry(this.ReadAsciiString(4));
}
/// <returns>The read entry.</returns>
public IccSignatureTagDataEntry ReadSignatureTagDataEntry() => new(this.ReadAsciiString(4));
/// <summary>
/// Reads a <see cref="IccTextTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
public IccTextTagDataEntry ReadTextTagDataEntry(uint size)
{
return new IccTextTagDataEntry(this.ReadAsciiString((int)size - 8)); // 8 is the tag header size
}
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccTextTagDataEntry ReadTextTagDataEntry(uint size) => new(this.ReadAsciiString((int)size - 8)); // 8 is the tag header size
/// <summary>
/// Reads a <see cref="IccUFix16ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUFix16ArrayTagDataEntry ReadUFix16ArrayTagDataEntry(uint size)
{
uint count = (size - 8) / 4;
@ -699,8 +682,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccUInt16ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUInt16ArrayTagDataEntry ReadUInt16ArrayTagDataEntry(uint size)
{
uint count = (size - 8) / 2;
@ -716,8 +699,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccUInt32ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUInt32ArrayTagDataEntry ReadUInt32ArrayTagDataEntry(uint size)
{
uint count = (size - 8) / 4;
@ -733,8 +716,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccUInt64ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUInt64ArrayTagDataEntry ReadUInt64ArrayTagDataEntry(uint size)
{
uint count = (size - 8) / 8;
@ -750,8 +733,8 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccUInt8ArrayTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccUInt8ArrayTagDataEntry ReadUInt8ArrayTagDataEntry(uint size)
{
int count = (int)size - 8; // 8 is the tag header size
@ -763,20 +746,17 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccViewingConditionsTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
public IccViewingConditionsTagDataEntry ReadViewingConditionsTagDataEntry()
{
return new IccViewingConditionsTagDataEntry(
/// <returns>The read entry.</returns>
public IccViewingConditionsTagDataEntry ReadViewingConditionsTagDataEntry() => new(
illuminantXyz: this.ReadXyzNumber(),
surroundXyz: this.ReadXyzNumber(),
illuminant: (IccStandardIlluminant)this.ReadUInt32());
}
/// <summary>
/// Reads a <see cref="IccXyzTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <returns>The read entry</returns>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry.</returns>
public IccXyzTagDataEntry ReadXyzTagDataEntry(uint size)
{
uint count = (size - 8) / 12;
@ -792,7 +772,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccTextDescriptionTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccTextDescriptionTagDataEntry ReadTextDescriptionTagDataEntry()
{
string unicodeValue, scriptcodeValue;
@ -832,7 +812,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccTextDescriptionTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccCrdInfoTagDataEntry ReadCrdInfoTagDataEntry()
{
uint productNameCount = this.ReadUInt32();
@ -856,7 +836,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccScreeningTagDataEntry"/>
/// </summary>
/// <returns>The read entry</returns>
/// <returns>The read entry.</returns>
public IccScreeningTagDataEntry ReadScreeningTagDataEntry()
{
var flags = (IccScreeningFlag)this.ReadInt32();
@ -873,7 +853,7 @@ internal sealed partial class IccDataReader
/// <summary>
/// Reads a <see cref="IccUcrBgTagDataEntry"/>
/// </summary>
/// <param name="size">The size of the entry in bytes</param>
/// <param name="size">The size of the entry in bytes.</param>
/// <returns>The read entry</returns>
public IccUcrBgTagDataEntry ReadUcrBgTagDataEntry(uint size)
{

59
src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.Lut.cs

@ -4,15 +4,15 @@
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
/// <content>
/// Provides methods to write ICC data types
/// Provides methods to write ICC data types.
/// </content>
internal sealed partial class IccDataWriter
{
/// <summary>
/// Writes an 8bit lookup table
/// Writes an 8bit lookup table.
/// </summary>
/// <param name="value">The LUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The LUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteLut8(IccLut value)
{
foreach (float item in value.Values)
@ -24,10 +24,10 @@ internal sealed partial class IccDataWriter
}
/// <summary>
/// Writes an 16bit lookup table
/// Writes an 16bit lookup table.
/// </summary>
/// <param name="value">The LUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The LUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteLut16(IccLut value)
{
foreach (float item in value.Values)
@ -39,10 +39,10 @@ internal sealed partial class IccDataWriter
}
/// <summary>
/// Writes an color lookup table
/// Writes an color lookup table.
/// </summary>
/// <param name="value">The CLUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The CLUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteClut(IccClut value)
{
int count = this.WriteArray(value.GridPointCount);
@ -67,57 +67,48 @@ internal sealed partial class IccDataWriter
}
/// <summary>
/// Writes a 8bit color lookup table
/// Writes a 8bit color lookup table.
/// </summary>
/// <param name="value">The CLUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The CLUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteClut8(IccClut value)
{
int count = 0;
foreach (float[] inArray in value.Values)
foreach (float item in value.Values)
{
foreach (float item in inArray)
{
count += this.WriteByte((byte)Numerics.Clamp((item * byte.MaxValue) + 0.5F, 0, byte.MaxValue));
}
count += this.WriteByte((byte)Numerics.Clamp((item * byte.MaxValue) + 0.5F, 0, byte.MaxValue));
}
return count;
}
/// <summary>
/// Writes a 16bit color lookup table
/// Writes a 16bit color lookup table.
/// </summary>
/// <param name="value">The CLUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The CLUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteClut16(IccClut value)
{
int count = 0;
foreach (float[] inArray in value.Values)
foreach (float item in value.Values)
{
foreach (float item in inArray)
{
count += this.WriteUInt16((ushort)Numerics.Clamp((item * ushort.MaxValue) + 0.5F, 0, ushort.MaxValue));
}
count += this.WriteUInt16((ushort)Numerics.Clamp((item * ushort.MaxValue) + 0.5F, 0, ushort.MaxValue));
}
return count;
}
/// <summary>
/// Writes a 32bit float color lookup table
/// Writes a 32bit float color lookup table.
/// </summary>
/// <param name="value">The CLUT to write</param>
/// <returns>The number of bytes written</returns>
/// <param name="value">The CLUT to write.</param>
/// <returns>The number of bytes written.</returns>
public int WriteClutF32(IccClut value)
{
int count = 0;
foreach (float[] inArray in value.Values)
foreach (float item in value.Values)
{
foreach (float item in inArray)
{
count += this.WriteSingle(item);
}
count += this.WriteSingle(item);
}
return count;

31
src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.Matrix.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors.
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
@ -61,15 +61,21 @@ internal sealed partial class IccDataWriter
public int WriteMatrix(in DenseMatrix<float> value, bool isSingle)
{
int count = 0;
for (int y = 0; y < value.Rows; y++)
if (isSingle)
{
for (int x = 0; x < value.Columns; x++)
for (int y = 0; y < value.Rows; y++)
{
if (isSingle)
for (int x = 0; x < value.Columns; x++)
{
count += this.WriteSingle(value[x, y]);
}
else
}
}
else
{
for (int y = 0; y < value.Rows; y++)
{
for (int x = 0; x < value.Columns; x++)
{
count += this.WriteFix16(value[x, y]);
}
@ -88,15 +94,22 @@ internal sealed partial class IccDataWriter
public int WriteMatrix(float[,] value, bool isSingle)
{
int count = 0;
for (int y = 0; y < value.GetLength(1); y++)
if (isSingle)
{
for (int x = 0; x < value.GetLength(0); x++)
for (int y = 0; y < value.GetLength(1); y++)
{
if (isSingle)
for (int x = 0; x < value.GetLength(0); x++)
{
count += this.WriteSingle(value[x, y]);
}
else
}
}
else
{
for (int y = 0; y < value.GetLength(1); y++)
{
for (int x = 0; x < value.GetLength(0); x++)
{
count += this.WriteFix16(value[x, y]);
}

2
src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs

@ -231,7 +231,7 @@ internal sealed partial class IccDataWriter
{
int count = this.WriteByte((byte)value.InputChannelCount);
count += this.WriteByte((byte)value.OutputChannelCount);
count += this.WriteByte((byte)value.ClutValues.Values[0].Length);
count += this.WriteByte((byte)value.ClutValues.OutputChannelCount);
count += this.WriteEmpty(1);
count += this.WriteMatrix(value.Matrix, false);

2
src/ImageSharp/Metadata/Profiles/ICC/Enums/IccFormulaCurveType.cs

@ -14,7 +14,7 @@ internal enum IccFormulaCurveType : ushort
Type1 = 0,
/// <summary>
/// Type 1: Y = a * log10 (b * X^γ + c) + d
/// Type 2: Y = a * log10 (b * X^γ + c) + d
/// </summary>
Type2 = 1,

2
src/ImageSharp/Metadata/Profiles/ICC/Exceptions/InvalidIccProfileException.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors.
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;

2
src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs

@ -190,7 +190,6 @@ public sealed class IccProfile : IDeepCloneable<IccProfile>
return;
}
IccReader reader = new();
this.header = IccReader.ReadHeader(this.data);
}
@ -207,7 +206,6 @@ public sealed class IccProfile : IDeepCloneable<IccProfile>
return;
}
IccReader reader = new();
this.entries = IccReader.ReadTagData(this.data);
}
}

21
src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs

@ -83,28 +83,19 @@ internal sealed class IccReader
{
IccTagTableEntry[] tagTable = ReadTagTable(reader);
List<IccTagDataEntry> entries = new(tagTable.Length);
Dictionary<uint, IccTagDataEntry> store = new();
foreach (IccTagTableEntry tag in tagTable)
{
IccTagDataEntry entry;
if (store.TryGetValue(tag.Offset, out IccTagDataEntry? value))
try
{
entry = value;
entry = reader.ReadTagDataEntry(tag);
}
else
catch
{
try
{
entry = reader.ReadTagDataEntry(tag);
}
catch
{
// Ignore tags that could not be read
continue;
}
store.Add(tag.Offset, entry);
// Ignore tags that could not be read
continue;
}
entry.TagSignature = tag.Signature;

6
src/ImageSharp/Metadata/Profiles/ICC/IccTagDataEntry.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors.
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
@ -41,9 +41,7 @@ public abstract class IccTagDataEntry : IEquatable<IccTagDataEntry>
/// <inheritdoc/>
public override bool Equals(object? obj)
{
return obj is IccTagDataEntry entry && this.Equals(entry);
}
=> obj is IccTagDataEntry entry && this.Equals(entry);
/// <inheritdoc/>
public virtual bool Equals(IccTagDataEntry? other)

100
src/ImageSharp/Metadata/Profiles/ICC/Various/IccClut.cs

@ -1,20 +1,21 @@
// Copyright (c) Six Labors.
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
/// <summary>
/// Color Lookup Table
/// Color Lookup Table.
/// </summary>
internal sealed class IccClut : IEquatable<IccClut>
{
/// <summary>
/// Initializes a new instance of the <see cref="IccClut"/> class.
/// </summary>
/// <param name="values">The CLUT values</param>
/// <param name="gridPointCount">The gridpoint count</param>
/// <param name="type">The data type of this CLUT</param>
public IccClut(float[][] values, byte[] gridPointCount, IccClutDataType type)
/// <param name="values">The CLUT values.</param>
/// <param name="gridPointCount">The gridpoint count.</param>
/// <param name="type">The data type of this CLUT.</param>
/// <param name="outputChannelCount">The output channels count.</param>
public IccClut(float[] values, byte[] gridPointCount, IccClutDataType type, int outputChannelCount)
{
Guard.NotNull(values, nameof(values));
Guard.NotNull(gridPointCount, nameof(gridPointCount));
@ -22,91 +23,33 @@ internal sealed class IccClut : IEquatable<IccClut>
this.Values = values;
this.DataType = type;
this.InputChannelCount = gridPointCount.Length;
this.OutputChannelCount = values[0].Length;
this.OutputChannelCount = outputChannelCount;
this.GridPointCount = gridPointCount;
this.CheckValues();
}
/// <summary>
/// Initializes a new instance of the <see cref="IccClut"/> class.
/// </summary>
/// <param name="values">The CLUT values</param>
/// <param name="gridPointCount">The gridpoint count</param>
public IccClut(ushort[][] values, byte[] gridPointCount)
{
Guard.NotNull(values, nameof(values));
Guard.NotNull(gridPointCount, nameof(gridPointCount));
const float Max = ushort.MaxValue;
this.Values = new float[values.Length][];
for (int i = 0; i < values.Length; i++)
{
this.Values[i] = new float[values[i].Length];
for (int j = 0; j < values[i].Length; j++)
{
this.Values[i][j] = values[i][j] / Max;
}
}
this.DataType = IccClutDataType.UInt16;
this.InputChannelCount = gridPointCount.Length;
this.OutputChannelCount = values[0].Length;
this.GridPointCount = gridPointCount;
this.CheckValues();
}
/// <summary>
/// Initializes a new instance of the <see cref="IccClut"/> class.
/// </summary>
/// <param name="values">The CLUT values</param>
/// <param name="gridPointCount">The gridpoint count</param>
public IccClut(byte[][] values, byte[] gridPointCount)
{
Guard.NotNull(values, nameof(values));
Guard.NotNull(gridPointCount, nameof(gridPointCount));
const float Max = byte.MaxValue;
this.Values = new float[values.Length][];
for (int i = 0; i < values.Length; i++)
{
this.Values[i] = new float[values[i].Length];
for (int j = 0; j < values[i].Length; j++)
{
this.Values[i][j] = values[i][j] / Max;
}
}
this.DataType = IccClutDataType.UInt8;
this.InputChannelCount = gridPointCount.Length;
this.OutputChannelCount = values[0].Length;
this.GridPointCount = gridPointCount;
this.CheckValues();
}
/// <summary>
/// Gets the values that make up this table
/// Gets the values that make up this table.
/// </summary>
public float[][] Values { get; }
public float[] Values { get; }
/// <summary>
/// Gets the CLUT data type (important when writing a profile)
/// Gets the CLUT data type (important when writing a profile).
/// </summary>
public IccClutDataType DataType { get; }
/// <summary>
/// Gets the number of input channels
/// Gets the number of input channels.
/// </summary>
public int InputChannelCount { get; }
/// <summary>
/// Gets the number of output channels
/// Gets the number of output channels.
/// </summary>
public int OutputChannelCount { get; }
/// <summary>
/// Gets the number of grid points per input channel
/// Gets the number of grid points per input channel.
/// </summary>
public byte[] GridPointCount { get; }
@ -134,15 +77,12 @@ internal sealed class IccClut : IEquatable<IccClut>
public override bool Equals(object? obj) => obj is IccClut other && this.Equals(other);
/// <inheritdoc/>
public override int GetHashCode()
{
return HashCode.Combine(
public override int GetHashCode() => HashCode.Combine(
this.Values,
this.DataType,
this.InputChannelCount,
this.OutputChannelCount,
this.GridPointCount);
}
private bool EqualsValuesArray(IccClut other)
{
@ -153,7 +93,7 @@ internal sealed class IccClut : IEquatable<IccClut>
for (int i = 0; i < this.Values.Length; i++)
{
if (!this.Values[i].AsSpan().SequenceEqual(other.Values[i]))
if (!this.Values.SequenceEqual(other.Values))
{
return false;
}
@ -167,17 +107,13 @@ internal sealed class IccClut : IEquatable<IccClut>
Guard.MustBeBetweenOrEqualTo(this.InputChannelCount, 1, 15, nameof(this.InputChannelCount));
Guard.MustBeBetweenOrEqualTo(this.OutputChannelCount, 1, 15, nameof(this.OutputChannelCount));
bool isLengthDifferent = this.Values.Any(t => t.Length != this.OutputChannelCount);
Guard.IsFalse(isLengthDifferent, nameof(this.Values), "The number of output values varies");
int length = 0;
for (int i = 0; i < this.InputChannelCount; i++)
{
length += (int)Math.Pow(this.GridPointCount[i], this.InputChannelCount);
}
length /= this.InputChannelCount;
Guard.IsTrue(this.Values.Length == length, nameof(this.Values), "Length of values array does not match the grid points");
// TODO: Disabled this check, not sure if this check is correct.
// Guard.IsTrue(this.Values.Length == length, nameof(this.Values), "Length of values array does not match the grid points");
}
}

10
src/ImageSharp/Metadata/Profiles/ICC/Various/IccTagTableEntry.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors.
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Metadata.Profiles.Icc;
@ -49,9 +49,7 @@ internal readonly struct IccTagTableEntry : IEquatable<IccTagTableEntry>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
public static bool operator ==(IccTagTableEntry left, IccTagTableEntry right)
{
return left.Equals(right);
}
=> left.Equals(right);
/// <summary>
/// Compares two <see cref="IccTagTableEntry"/> objects for equality.
@ -62,9 +60,7 @@ internal readonly struct IccTagTableEntry : IEquatable<IccTagTableEntry>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
public static bool operator !=(IccTagTableEntry left, IccTagTableEntry right)
{
return !left.Equals(right);
}
=> !left.Equals(right);
/// <inheritdoc/>
public override bool Equals(object? obj) => obj is IccTagTableEntry other && this.Equals(other);

3
src/ImageSharp/PixelFormats/IPixel.cs

@ -23,7 +23,8 @@ public interface IPixel<TSelf> : IPixel, IEquatable<TSelf>
static abstract PixelOperations<TSelf> CreatePixelOperations();
/// <summary>
/// Initializes the pixel instance from a generic scaled <see cref="Vector4"/>.
/// Initializes the pixel instance from a generic a generic ("scaled") <see cref="Vector4"/> representation
/// with values scaled and clamped between <value>0</value> and <value>1</value>
/// </summary>
/// <param name="source">The vector to load the pixel from.</param>
/// <returns>The <typeparamref name="TSelf"/>.</returns>

3
src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs

@ -61,7 +61,8 @@ public partial struct Rgb24 : IPixel<Rgb24>
/// <param name="color">The instance of <see cref="Rgb"/> to convert.</param>
/// <returns>An instance of <see cref="Rgb24"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Rgb24(Rgb color) => FromScaledVector4(new Vector4(color.ToVector3(), 1f));
public static implicit operator Rgb24(Rgb color)
=> FromScaledVector4(new Vector4(color.ToScaledVector3(), 1F));
/// <summary>
/// Compares two <see cref="Rgb24"/> objects for equality.

2
src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs

@ -187,7 +187,7 @@ public partial struct Rgba32 : IPixel<Rgba32>, IPackedVector<uint>
/// <param name="color">The instance of <see cref="Rgb"/> to convert.</param>
/// <returns>An instance of <see cref="Rgba32"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Rgba32(Rgb color) => FromScaledVector4(new Vector4(color.ToVector3(), 1F));
public static implicit operator Rgba32(Rgb color) => FromScaledVector4(new Vector4(color.ToScaledVector3(), 1F));
/// <summary>
/// Compares two <see cref="Rgba32"/> objects for equality.

2
tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs

@ -13,7 +13,7 @@ public class RgbWorkingSpaceAdapt
private static readonly RGBColor RGBColor = new(0.206162, 0.260277, 0.746717);
private static readonly ColorProfileConverter ColorProfileConverter = new(new ColorConversionOptions { RgbWorkingSpace = KnownRgbWorkingSpaces.WideGamutRgb, TargetRgbWorkingSpace = KnownRgbWorkingSpaces.SRgb });
private static readonly ColorProfileConverter ColorProfileConverter = new(new ColorConversionOptions { SourceRgbWorkingSpace = KnownRgbWorkingSpaces.WideGamutRgb, TargetRgbWorkingSpace = KnownRgbWorkingSpaces.SRgb });
private static readonly IColorConverter<RGBColor, RGBColor> ColourfulConverter = new ConverterBuilder().FromRGB(RGBWorkingSpaces.WideGamutRGB).ToRGB(RGBWorkingSpaces.sRGB).Build();

12
tests/ImageSharp.Tests/ColorProfiles/ApproximateColorProfileComparer.cs

@ -22,7 +22,9 @@ internal readonly struct ApproximateColorProfileComparer :
IEqualityComparer<Cmyk>,
IEqualityComparer<Hsl>,
IEqualityComparer<Hsv>,
IEqualityComparer<HunterLab>
IEqualityComparer<HunterLab>,
IEqualityComparer<Y>,
IEqualityComparer<YccK>
{
private readonly float epsilon;
@ -58,6 +60,10 @@ internal readonly struct ApproximateColorProfileComparer :
public bool Equals(HunterLab x, HunterLab y) => this.Equals(x.L, y.L) && this.Equals(x.A, y.A) && this.Equals(x.B, y.B);
public bool Equals(Y x, Y y) => this.Equals(x.L, y.L);
public bool Equals(YccK x, YccK y) => this.Equals(x.Y, y.Y) && this.Equals(x.Cb, y.Cb) && this.Equals(x.Cr, y.Cr) && this.Equals(x.K, y.K);
public int GetHashCode([DisallowNull] CieLab obj) => obj.GetHashCode();
public int GetHashCode([DisallowNull] CieXyz obj) => obj.GetHashCode();
@ -84,6 +90,10 @@ internal readonly struct ApproximateColorProfileComparer :
public int GetHashCode([DisallowNull] HunterLab obj) => obj.GetHashCode();
public int GetHashCode([DisallowNull] Y obj) => obj.GetHashCode();
public int GetHashCode([DisallowNull] YccK obj) => obj.GetHashCode();
private bool Equals(float x, float y)
{
float d = x - y;

5
tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLchConversionTests.cs

@ -12,6 +12,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// Test data generated using:
/// <see href="http://www.brucelindbloom.com/index.html?ColorCalculator.html"/>
/// </remarks>
[Trait("Color", "Conversion")]
public class CieLabAndCieLchConversionTests
{
private static readonly ApproximateColorProfileComparer Comparer = new(.0001f);
@ -30,7 +31,7 @@ public class CieLabAndCieLchConversionTests
// Arrange
CieLch input = new(l, c, h);
CieLab expected = new(l2, a, b);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLch> inputSpan = new CieLch[5];
@ -65,7 +66,7 @@ public class CieLabAndCieLchConversionTests
// Arrange
CieLab input = new(l, a, b);
CieLch expected = new(l2, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLab> inputSpan = new CieLab[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLchuvConversionTests.cs

@ -24,7 +24,7 @@ public class CieLabAndCieLchuvConversionTests
// Arrange
CieLchuv input = new(l, c, h);
CieLab expected = new(l2, a, b);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLchuv> inputSpan = new CieLchuv[5];
@ -53,7 +53,7 @@ public class CieLabAndCieLchuvConversionTests
// Arrange
CieLab input = new(l, a, b);
CieLchuv expected = new(l2, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLab> inputSpan = new CieLab[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLabAndCieLuvConversionTests.cs

@ -24,7 +24,7 @@ public class CieLabAndCieLuvConversionTests
// Arrange
CieLuv input = new(l, u, v);
CieLab expected = new(l2, a, b);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -53,7 +53,7 @@ public class CieLabAndCieLuvConversionTests
// Arrange
CieLab input = new(l, a, b);
CieLuv expected = new(l2, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLab> inputSpan = new CieLab[5];

10
tests/ImageSharp.Tests/ColorProfiles/CieLabAndYCbCrConversionTests.cs

@ -13,8 +13,9 @@ public class CieLabAndYCbCrConversionTests
private static readonly ApproximateColorProfileComparer Comparer = new(.0002F);
[Theory]
[InlineData(0, 128, 128, 0, 0, 0)]
[InlineData(87.4179, 133.9763, 247.5308, 55.06287, 82.54838, 23.1697)]
[InlineData(1, .5F, .5F, 100, 0, 0)]
[InlineData(0, .5F, .5F, 0, 0, 0)]
[InlineData(.5F, .5F, .5F, 53.38897F, 0, 0)]
public void Convert_YCbCr_to_CieLab(float y, float cb, float cr, float l, float a, float b)
{
// Arrange
@ -41,8 +42,9 @@ public class CieLabAndYCbCrConversionTests
}
[Theory]
[InlineData(0, 0, 0, 0, 128, 128)]
[InlineData(55.06287, 82.54838, 23.1697, 87.41701, 133.97232, 247.5314)]
[InlineData(100, 0, 0, 1, .5F, .5F)]
[InlineData(0, 0, 0, 0, .5F, .5F)]
[InlineData(53.38897F, 0, 0, .5F, .5F, .5F)]
public void Convert_CieLab_to_YCbCr(float l, float a, float b, float y, float cb, float cr)
{
// Arrange

1
tests/ImageSharp.Tests/ColorProfiles/CieLabTests.cs

@ -9,6 +9,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// <summary>
/// Tests the <see cref="CieLab"/> struct.
/// </summary>
[Trait("Color", "Conversion")]
public class CieLabTests
{
[Fact]

4
tests/ImageSharp.Tests/ColorProfiles/CieLchAndCieLuvConversionTests.cs

@ -20,7 +20,7 @@ public class CieLchAndCieLuvConversionTests
// Arrange
CieLch input = new(l, c, h);
CieLuv expected = new(l2, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLch> inputSpan = new CieLch[5];
@ -48,7 +48,7 @@ public class CieLchAndCieLuvConversionTests
// Arrange
CieLuv input = new(l2, u, v);
CieLch expected = new(l, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCieLchConversionTests.cs

@ -20,7 +20,7 @@ public class CieLchuvAndCieLchConversionTests
// Arrange
CieLch input = new(l2, c2, h2);
CieLchuv expected = new(l, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLch> inputSpan = new CieLch[5];
@ -48,7 +48,7 @@ public class CieLchuvAndCieLchConversionTests
// Arrange
CieLchuv input = new(l, c, h);
CieLch expected = new(l2, c2, h2);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLchuv> inputSpan = new CieLchuv[5];

5
tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCieLuvConversionTests.cs

@ -12,6 +12,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// Test data generated using:
/// <see href="http://www.brucelindbloom.com/index.html?ColorCalculator.html"/>
/// </remarks>
[Trait("Color", "Conversion")]
public class CieLchuvAndCieLuvConversionTests
{
private static readonly ApproximateColorProfileComparer Comparer = new(.0001F);
@ -30,7 +31,7 @@ public class CieLchuvAndCieLuvConversionTests
// Arrange
CieLchuv input = new(l, c, h);
CieLuv expected = new(l2, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLchuv> inputSpan = new CieLchuv[5];
@ -66,7 +67,7 @@ public class CieLchuvAndCieLuvConversionTests
// Arrange
CieLuv input = new(l, u, v);
CieLchuv expected = new(l2, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLchuvAndCmykConversionTests.cs

@ -20,7 +20,7 @@ public class CieLchuvAndCmykConversionTests
// Arrange
Cmyk input = new(c2, m, y, k);
CieLchuv expected = new(l, c, h);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<Cmyk> inputSpan = new Cmyk[5];
@ -49,7 +49,7 @@ public class CieLchuvAndCmykConversionTests
// Arrange
CieLchuv input = new(l, c, h);
Cmyk expected = new(c2, m, y, k);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLchuv> inputSpan = new CieLchuv[5];

1
tests/ImageSharp.Tests/ColorProfiles/CieLchuvTests.cs

@ -9,6 +9,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// <summary>
/// Tests the <see cref="CieLchuv"/> struct.
/// </summary>
[Trait("Color", "Conversion")]
public class CieLchuvTests
{
[Fact]

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndCieXyyConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndCieXyyConversionTests
// Arrange
CieLuv input = new(l, u, v);
CieXyy expected = new(x, y, yl);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndCieXyyConversionTests
// Arrange
CieXyy input = new(x, y, yl);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieXyy> inputSpan = new CieXyy[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHslConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndHslConversionTests
// Arrange
CieLuv input = new(l, u, v);
Hsl expected = new(h, s, l2);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndHslConversionTests
// Arrange
Hsl input = new(h, s, l2);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<Hsl> inputSpan = new Hsl[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHsvConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndHsvConversionTests
// Arrange
CieLuv input = new(l, u, v);
Hsv expected = new(h, s, v2);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndHsvConversionTests
// Arrange
Hsv input = new(h, s, v2);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<Hsv> inputSpan = new Hsv[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndHunterLabConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndHunterLabConversionTests
// Arrange
CieLuv input = new(l, u, v);
HunterLab expected = new(l2, a, b);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D50 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndHunterLabConversionTests
// Arrange
HunterLab input = new(l2, a, b);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D50, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<HunterLab> inputSpan = new HunterLab[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndLmsConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndLmsConversionTests
// Arrange
CieLuv input = new(l, u, v);
Lms expected = new(l2, m, s);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndLmsConversionTests
// Arrange
Lms input = new(l2, m, s);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<Lms> inputSpan = new Lms[5];

4
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndRgbConversionTests.cs

@ -20,7 +20,7 @@ public class CieLuvAndRgbConversionTests
// Arrange
CieLuv input = new(l, u, v);
Rgb expected = new(r, g, b);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -49,7 +49,7 @@ public class CieLuvAndRgbConversionTests
// Arrange
Rgb input = new(r, g, b);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<Rgb> inputSpan = new Rgb[5];

14
tests/ImageSharp.Tests/ColorProfiles/CieLuvAndYCbCrConversionTests.cs

@ -13,14 +13,15 @@ public class CieLuvAndYCbCrConversionTests
private static readonly ApproximateColorProfileComparer Comparer = new(.0002F);
[Theory]
[InlineData(0, 0, 0, 0, 128, 128)]
[InlineData(36.0555, 93.6901, 10.01514, 71.8283, 119.3174, 193.9839)]
[InlineData(100, 0, 0, 1, .5F, .5F)]
[InlineData(0, 0, 0, 0, .5F, .5F)]
[InlineData(53.38897F, 0, 0, .5F, .5F, .5F)]
public void Convert_CieLuv_to_YCbCr(float l, float u, float v, float y, float cb, float cr)
{
// Arrange
CieLuv input = new(l, u, v);
YCbCr expected = new(y, cb, cr);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<CieLuv> inputSpan = new CieLuv[5];
@ -42,14 +43,15 @@ public class CieLuvAndYCbCrConversionTests
}
[Theory]
[InlineData(0, 128, 128, 0, 0, 0)]
[InlineData(71.8283, 119.3174, 193.9839, 36.00565, 93.44593, 10.2234)]
[InlineData(1, .5F, .5F, 100, 0, 0)]
[InlineData(0, .5F, .5F, 0, 0, 0)]
[InlineData(.5F, .5F, .5F, 53.38897F, 0, 0)]
public void Convert_YCbCr_to_CieLuv(float y, float cb, float cr, float l, float u, float v)
{
// Arrange
YCbCr input = new(y, cb, cr);
CieLuv expected = new(l, u, v);
ColorConversionOptions options = new() { WhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorConversionOptions options = new() { SourceWhitePoint = KnownIlluminants.D65, TargetWhitePoint = KnownIlluminants.D65 };
ColorProfileConverter converter = new(options);
Span<YCbCr> inputSpan = new YCbCr[5];

1
tests/ImageSharp.Tests/ColorProfiles/CieLuvTests.cs

@ -9,6 +9,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// <summary>
/// Tests the <see cref="CieLuv"/> struct.
/// </summary>
[Trait("Color", "Conversion")]
public class CieLuvTests
{
[Fact]

1
tests/ImageSharp.Tests/ColorProfiles/CieXyChromaticityCoordinatesTests.cs

@ -8,6 +8,7 @@ namespace SixLabors.ImageSharp.Tests.ColorProfiles;
/// <summary>
/// Tests the <see cref="CieXyChromaticityCoordinates"/> struct.
/// </summary>
[Trait("Color", "Conversion")]
public class CieXyChromaticityCoordinatesTests
{
[Fact]

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save