diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18de46d..a8873a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## Unreleased
+
+Added:
+
+- `Image.DecodeCmyk` decodes a CMYK JPEG (YCCK included) or separated TIFF as its inks instead of sRGB: a `CmykImage` of four planes, 0 no ink to 255 full, with the file's CMYK profile, for print work such as a PDF's `DeviceCMYK`. `Map` resizes, crops or turns every plane alike, `ToInterleaved` gives C, M, Y, K per pixel and `ToSrgb` converts for the screen. Shrink-on-load and orientation work as for `Decode`, and it takes the same time. See [docs/cmyk.md](docs/cmyk.md).
+
+Changed:
+
+- The canvas (`Zorg.Imaging.Drawing`) is no longer marked experimental: using it doesn't need the diagnostic `ZORGDRAW` suppressed any more. A project that suppressed it can drop the `NoWarn`.
+
## 0.4.0
What a program that handles the pixels itself needs, asked for by Zorg.Pdf: reading an image out of a larger buffer without copying it, shrink-on-load without the pipeline, converting between pixel layouts, and telling whether an alpha channel is used. And a canvas, new and experimental, for page previews, charts and badges. Everything the library already did gives the same output at the same speed as 0.3.0.
diff --git a/README.md b/README.md
index 36b6e9f..3046ab6 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
Managed image decoding, resizing and encoding for .NET 10, written in C# only. PNG, JPEG, GIF and WebP (with animations), plus BMP and TIFF decoding, in one package, with no native binaries and no NuGet dependencies.
-**Status: 0.4, on NuGet as `Zorg.Imaging` (and `Zorg.Imaging.SystemCodecs`). The API may still change before 1.0. It can recognise image formats and read their headers (`ImageFormats.Detect`, `Image.Identify`), decode and encode PNG (with an oxipng-style optimiser) and JPEG, decode and encode WebP (lossy, lossless and near-lossless) and GIF, decode BMP and TIFF, keeping the colour space (`Image.Decode`, `SaveAsPng`, `SaveAsJpeg`, `SaveAsWebp`, `SaveAsGif`), and resize, fit, crop, turn, flatten, blur, sharpen, watermark and trim images, make BlurHash placeholders, one at a time or as a pipeline (`ImagePipeline.Load(...).Fit(...).SaveAsync(...)`; see [docs/pipeline.md](docs/pipeline.md)), read and write animated GIF and WebP frame by frame (`AnimationReader`, `AnimationWriter`; see [docs/animation.md](docs/animation.md)), and, new and experimental, draw shapes, outlines and images on a canvas ([docs/drawing.md](docs/drawing.md)).** Other packages can add decoders for AVIF, HEIC and the other formats it only recognises ([docs/codecs.md](docs/codecs.md)); `Zorg.Imaging.SystemCodecs` decodes AVIF and HEIC through Windows' and macOS's own decoders. What isn't supported yet is in [docs/limits.md](docs/limits.md).
+**Status: 0.4, on NuGet as `Zorg.Imaging` (and `Zorg.Imaging.SystemCodecs`). The API may still change before 1.0. It can recognise image formats and read their headers (`ImageFormats.Detect`, `Image.Identify`), decode and encode PNG (with an oxipng-style optimiser) and JPEG, decode and encode WebP (lossy, lossless and near-lossless) and GIF, decode BMP and TIFF, keeping the colour space (`Image.Decode`, `SaveAsPng`, `SaveAsJpeg`, `SaveAsWebp`, `SaveAsGif`), and resize, fit, crop, turn, flatten, blur, sharpen, watermark and trim images, make BlurHash placeholders, one at a time or as a pipeline (`ImagePipeline.Load(...).Fit(...).SaveAsync(...)`; see [docs/pipeline.md](docs/pipeline.md)), read and write animated GIF and WebP frame by frame (`AnimationReader`, `AnimationWriter`; see [docs/animation.md](docs/animation.md)), and draw shapes, outlines and images on a canvas ([docs/drawing.md](docs/drawing.md)).** Other packages can add decoders for AVIF, HEIC and the other formats it only recognises ([docs/codecs.md](docs/codecs.md)); `Zorg.Imaging.SystemCodecs` decodes AVIF and HEIC through Windows' and macOS's own decoders. What isn't supported yet is in [docs/limits.md](docs/limits.md).
## Goals
diff --git a/benchmarks/Zorg.Imaging.Benchmarks/Zorg.Imaging.Benchmarks.csproj b/benchmarks/Zorg.Imaging.Benchmarks/Zorg.Imaging.Benchmarks.csproj
index cc456ca..3576a02 100644
--- a/benchmarks/Zorg.Imaging.Benchmarks/Zorg.Imaging.Benchmarks.csproj
+++ b/benchmarks/Zorg.Imaging.Benchmarks/Zorg.Imaging.Benchmarks.csproj
@@ -3,8 +3,6 @@
Exe
false
-
- $(NoWarn);ZORGDRAW
diff --git a/docs/cmyk.md b/docs/cmyk.md
new file mode 100644
index 0000000..68c36dc
--- /dev/null
+++ b/docs/cmyk.md
@@ -0,0 +1,31 @@
+# CMYK
+
+A CMYK file (a four-component JPEG, YCCK included, or a separated TIFF) normally decodes to sRGB: `Image.Decode`
+converts the inks through the file's CMYK profile, or by the device formula when it has none. That's what the web
+wants, and every operation and encoder works on the result.
+
+Print work wants the inks themselves, for example to write a PDF image as `DeviceCMYK`. `Image.DecodeCmyk` gives
+them as a `CmykImage`: four `L8` planes, cyan, magenta, yellow and black, each from 0 (no ink) to 255 (full ink),
+with the file's CMYK profile. It returns `null` for an image that isn't CMYK.
+
+```csharp
+using CmykImage? inks = Image.DecodeCmyk(jpeg, new DecodeOptions { ShrinkTo = (1200, 1200) });
+if (inks is not null)
+{
+ using CmykImage fitted = inks.Map(plane => plane.Fit(1200, 1200));
+ byte[] deviceCmyk = fitted.ToInterleaved(); // C, M, Y, K per pixel, as a PDF image stream holds them
+ ReadOnlyMemory profile = fitted.IccProfile; // for /ICCBased with /N 4, or empty for device CMYK
+}
+```
+
+- The orientation is applied and `DecodeOptions.ShrinkTo` works as for `Decode`; `DecodeOptions.PixelFormat` doesn't
+ apply.
+- `Map` runs one operation on each plane: `Fit`, `Resize`, `Crop`, `Rotate`, `Flip...`. The planes are in
+ `ColorSpace.LinearSrgb`, so resizing blends ink amounts directly, as print software does, with no gamma.
+- `ToSrgb` converts back for the screen, through the profile when there is one: the same pixels `Decode` gives.
+
+There is no CMYK pixel format: the effects and encoders work on RGB, so a CMYK picture stays four planes until it's
+written elsewhere (as a PDF does) or converted with `ToSrgb`.
+
+A 4000 x 3000 CMYK JPEG decodes to its inks in the same time as to sRGB (103 against 99 ms, one core of the
+development machine); with shrink-on-load, a fit to 1200 pixels and interleaving, 122 ms.
diff --git a/docs/drawing.md b/docs/drawing.md
index db591d9..2e54659 100644
--- a/docs/drawing.md
+++ b/docs/drawing.md
@@ -1,12 +1,7 @@
# Drawing
`Canvas` draws shapes, lines and images into an `Image`, anti-aliased by exact pixel coverage. It is made for
-previews of pages (PDF), charts and badges. It is new: the API may change, or move to a package of its own, so using it
-needs the diagnostic `ZORGDRAW` suppressed.
-
-```xml
-$(NoWarn);ZORGDRAW
-```
+previews of pages (PDF), charts and badges.
```csharp
using System.Numerics;
diff --git a/samples/Zorg.Imaging.AotSmoke/Zorg.Imaging.AotSmoke.csproj b/samples/Zorg.Imaging.AotSmoke/Zorg.Imaging.AotSmoke.csproj
index 45f6e4c..a9d7a6b 100644
--- a/samples/Zorg.Imaging.AotSmoke/Zorg.Imaging.AotSmoke.csproj
+++ b/samples/Zorg.Imaging.AotSmoke/Zorg.Imaging.AotSmoke.csproj
@@ -6,8 +6,6 @@
false
true
-
- $(NoWarn);ZORGDRAW
diff --git a/src/Zorg.Imaging/Codecs/Jpeg/JpegCmyk.cs b/src/Zorg.Imaging/Codecs/Jpeg/JpegCmyk.cs
index 13f4d84..80bccae 100644
--- a/src/Zorg.Imaging/Codecs/Jpeg/JpegCmyk.cs
+++ b/src/Zorg.Imaging/Codecs/Jpeg/JpegCmyk.cs
@@ -16,8 +16,9 @@ namespace Zorg.Imaging.Codecs.Jpeg;
/// three components are YCbCr of the inverted C, M and Y; without the marker the values are ink as they are.
///
///
-/// There is no CMYK pixel format, so the result is always sRGB: converted by the profile's own perceptual table, which
-/// is what the profile says the colours are, or by the device formula when there is no profile to say.
+/// There is no CMYK pixel format, so the result is sRGB: converted by the profile's own perceptual table, which is what
+/// the profile says the colours are, or by the device formula when there is no profile to say. For
+/// it is the inks themselves, in the four bytes of each pixel.
///
///
internal sealed class JpegCmyk
@@ -26,12 +27,16 @@ internal sealed class JpegCmyk
private readonly IccLookup? _profile;
private readonly Quantizer _encode = TransferFunction.For(ColorSpace.Srgb).Encoder(sixteen: false);
- private JpegCmyk(Storage storage, IccLookup? profile)
+ private JpegCmyk(Storage storage, IccLookup? profile, bool keepInks)
{
_storage = storage;
_profile = profile;
+ KeepInks = keepInks;
}
+ /// Whether writes the inks themselves, C, M, Y, K in four bytes, instead of sRGB.
+ public bool KeepInks { get; }
+
/// How the four components hold the inks.
public enum Storage
{
@@ -46,7 +51,7 @@ public enum Storage
}
/// The conversion for a file's Adobe transform (-1 when it has no Adobe marker) and its ICC profile.
- public static JpegCmyk For(int adobeTransform, ReadOnlySpan profile)
+ public static JpegCmyk For(int adobeTransform, ReadOnlySpan profile, bool keepInks = false)
{
Storage storage = adobeTransform switch
{
@@ -56,12 +61,12 @@ public static JpegCmyk For(int adobeTransform, ReadOnlySpan profile)
};
IccLookup? lookup = null;
- if (!profile.IsEmpty && IccProfileReader.Read(profile) is { LutChannels: 4, Lut: { } lut })
+ if (!keepInks && !profile.IsEmpty && IccProfileReader.Read(profile) is { LutChannels: 4, Lut: { } lut })
{
lookup = IccLookup.Build(lut, ColourMath.Invert(ColourMath.RgbToPcs(ColourMath.Chromaticities(1)!)));
}
- return new JpegCmyk(storage, lookup);
+ return new JpegCmyk(storage, lookup, keepInks);
}
/// Whether a profile does the conversion (otherwise the device formula).
@@ -70,6 +75,17 @@ public static JpegCmyk For(int adobeTransform, ReadOnlySpan profile)
/// Writes one row: four planes' samples in, pixels in out.
public void WriteRow(byte[][] rows, Span output, PixelFormat format, int width)
{
+ if (KeepInks)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ (int c, int m, int y, int k) = Inks(rows[0][x], rows[1][x], rows[2][x], rows[3][x]);
+ (output[4 * x], output[(4 * x) + 1], output[(4 * x) + 2], output[(4 * x) + 3]) = ((byte)c, (byte)m, (byte)y, (byte)k);
+ }
+
+ return;
+ }
+
Span device = stackalloc float[4];
for (int x = 0; x < width; x++)
{
diff --git a/src/Zorg.Imaging/Codecs/Jpeg/JpegDecoder.cs b/src/Zorg.Imaging/Codecs/Jpeg/JpegDecoder.cs
index d1a7615..e5d9934 100644
--- a/src/Zorg.Imaging/Codecs/Jpeg/JpegDecoder.cs
+++ b/src/Zorg.Imaging/Codecs/Jpeg/JpegDecoder.cs
@@ -171,10 +171,13 @@ marker is 0xC3 or 0xC7 or 0xCB or 0xCF ? "Lossless JPEG isn't supported."
reader.Finish();
ColorSpace colorSpace = state.ResolveColorSpace();
JpegCmyk? cmyk = null;
+ byte[]? inkProfile = null;
if (state.Frame.Components.Length == 4)
{
- // There is no CMYK pixel format: the pixels come out as sRGB, through the profile when there is one.
- cmyk = JpegCmyk.For(state.AdobeTransform, colorSpace.IccProfile.Span);
+ // There is no CMYK pixel format: the pixels come out as sRGB, through the profile when there is one, or,
+ // for Image.DecodeCmyk, as the inks themselves.
+ cmyk = JpegCmyk.For(state.AdobeTransform, colorSpace.IccProfile.Span, options.KeepInks);
+ inkProfile = options.KeepInks ? colorSpace.IccProfile.ToArray() : null;
colorSpace = ColorSpace.Srgb;
}
@@ -193,6 +196,7 @@ marker is 0xC3 or 0xC7 or 0xCB or 0xCF ? "Lossless JPEG isn't supported."
Image result = image;
image = null;
+ result.InkProfile = inkProfile;
return result;
}
finally
diff --git a/src/Zorg.Imaging/Codecs/Jpeg/JpegHeaderReader.cs b/src/Zorg.Imaging/Codecs/Jpeg/JpegHeaderReader.cs
index f8f9454..cc3b07d 100644
--- a/src/Zorg.Imaging/Codecs/Jpeg/JpegHeaderReader.cs
+++ b/src/Zorg.Imaging/Codecs/Jpeg/JpegHeaderReader.cs
@@ -100,6 +100,7 @@ public static async ValueTask ReadAsync(HeaderReader reader, Identify
HasExif = hasExif,
HasIccProfile = hasIcc,
ColorSpace = colorSpace,
+ IsCmyk = scratch[5] == 4,
};
}
diff --git a/src/Zorg.Imaging/Codecs/Jpeg/JpegOutput.cs b/src/Zorg.Imaging/Codecs/Jpeg/JpegOutput.cs
index 20a503f..2947f87 100644
--- a/src/Zorg.Imaging/Codecs/Jpeg/JpegOutput.cs
+++ b/src/Zorg.Imaging/Codecs/Jpeg/JpegOutput.cs
@@ -77,7 +77,8 @@ public static Image Compose(JpegFrame frame, int scale, Plane[] planes, bool isR
int width = JpegFrame.DivideUp((long)frame.Width * scale, 8);
int height = JpegFrame.DivideUp((long)frame.Height * scale, 8);
bool grey = frame.Components.Length == 1;
- PixelFormat format = requested != PixelFormat.None ? requested : grey ? PixelFormat.L8 : PixelFormat.Rgb24;
+ PixelFormat format = cmyk is { KeepInks: true } ? PixelFormat.Rgba32
+ : requested != PixelFormat.None ? requested : grey ? PixelFormat.L8 : PixelFormat.Rgb24;
var image = new Image(width, height, format);
try
{
diff --git a/src/Zorg.Imaging/Codecs/Tiff/TiffDecoder.cs b/src/Zorg.Imaging/Codecs/Tiff/TiffDecoder.cs
index bfd1a9c..2b35825 100644
--- a/src/Zorg.Imaging/Codecs/Tiff/TiffDecoder.cs
+++ b/src/Zorg.Imaging/Codecs/Tiff/TiffDecoder.cs
@@ -34,6 +34,7 @@ public static async ValueTask DecodeAsync(DataReader reader, DecodeOption
ReadOnlyMemory file = await ReadAllAsync(reader, options.Limits, cancellationToken).ConfigureAwait(false);
TiffDirectory directory = TiffDirectory.Read(file.Span, options.Limits);
Image image = Decode(file, directory, options);
+ bool inks = options.KeepInks && directory.Photometric == TiffDirectory.Separated;
if (options.ApplyOrientation && directory.Orientation is > 1 and <= 8)
{
try
@@ -49,6 +50,7 @@ public static async ValueTask DecodeAsync(DataReader reader, DecodeOption
}
}
+ image.InkProfile = inks ? directory.IccProfile ?? [] : null;
return image;
}
@@ -317,6 +319,11 @@ private static Image ToImage(byte[] pixels, TiffDirectory d, DecodeOptions optio
natural = alpha ? PixelFormat.Rgba32 : PixelFormat.Rgb24;
}
+ if (options.KeepInks && d.Photometric == TiffDirectory.Separated)
+ {
+ return Inks(pixels, d, width, height, samples, sixteen);
+ }
+
// Read every pixel as 16-bit RGBA, straight alpha, then write it in the format asked for.
var result = new Image(width, height, natural) { ColorSpace = colorSpace };
try
@@ -398,6 +405,29 @@ private static Image ToImage(byte[] pixels, TiffDirectory d, DecodeOptions optio
return result;
}
+ /// A separated (CMYK) TIFF's inks as they are, C, M, Y and K in four bytes, 0 no ink to 255 full.
+ private static Image Inks(byte[] pixels, TiffDirectory d, int width, int height, int samples, bool sixteen)
+ {
+ int maximum = sixteen ? 65535 : d.Bits < 8 ? (1 << d.Bits) - 1 : 255;
+ int sampleBytes = sixteen ? 2 : 1;
+ var result = new Image(width, height, PixelFormat.Rgba32);
+ for (int y = 0; y < height; y++)
+ {
+ ReadOnlySpan source = pixels.AsSpan((int)((long)y * width * samples * sampleBytes), width * samples * sampleBytes);
+ Span row = result.GetRowBytes(y);
+ for (int x = 0; x < width; x++)
+ {
+ for (int s = 0; s < 4; s++)
+ {
+ int v = Sample(source, samples, sixteen, x, s);
+ row[(4 * x) + s] = (byte)(maximum == 255 ? v : ((v * 255) + (maximum / 2)) / maximum);
+ }
+ }
+ }
+
+ return result;
+ }
+
private static int Sample(ReadOnlySpan row, int samples, bool sixteen, int x, int s) =>
sixteen ? MemoryMarshal.Read(row[(((x * samples) + s) * 2)..]) : row[(x * samples) + s];
diff --git a/src/Zorg.Imaging/Codecs/Tiff/TiffHeaderReader.cs b/src/Zorg.Imaging/Codecs/Tiff/TiffHeaderReader.cs
index f5be609..47cffc6 100644
--- a/src/Zorg.Imaging/Codecs/Tiff/TiffHeaderReader.cs
+++ b/src/Zorg.Imaging/Codecs/Tiff/TiffHeaderReader.cs
@@ -104,6 +104,7 @@ public static async ValueTask ReadAsync(HeaderReader reader, Identify
HasIccProfile = icc,
HasExif = exif,
ColorSpace = options.ReadColorSpace && !icc ? ColorSpace.Srgb : null,
+ IsCmyk = photometric == 5,
};
}
}
diff --git a/src/Zorg.Imaging/DecodeOptions.cs b/src/Zorg.Imaging/DecodeOptions.cs
index 631186a..f95e27e 100644
--- a/src/Zorg.Imaging/DecodeOptions.cs
+++ b/src/Zorg.Imaging/DecodeOptions.cs
@@ -137,6 +137,23 @@ public int MaxDegreeOfParallelism
private readonly Func? _shrinkToTarget;
+ ///
+ /// For : a CMYK file's pixels come out as its inks, C, M, Y and K in the four bytes of
+ /// an image, 0 no ink to 255 full, with set.
+ ///
+ internal bool KeepInks { get; init; }
+
+ internal DecodeOptions WithInks() => new()
+ {
+ Limits = Limits,
+ ApplyOrientation = ApplyOrientation,
+ MaxDegreeOfParallelism = MaxDegreeOfParallelism,
+ Codecs = Codecs,
+ ShrinkTo = ShrinkTo,
+ ShrinkTarget = ShrinkTarget,
+ KeepInks = true,
+ };
+
internal DecodeOptions WithShrinkTarget(Func? target) => new()
{
Limits = Limits,
@@ -145,5 +162,6 @@ public int MaxDegreeOfParallelism
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
Codecs = Codecs,
ShrinkTarget = target, // not ShrinkTo: the target given replaces it, even when null
+ KeepInks = KeepInks,
};
}
diff --git a/src/Zorg.Imaging/Drawing/Canvas.cs b/src/Zorg.Imaging/Drawing/Canvas.cs
index 0026413..8cfe128 100644
--- a/src/Zorg.Imaging/Drawing/Canvas.cs
+++ b/src/Zorg.Imaging/Drawing/Canvas.cs
@@ -23,8 +23,7 @@ namespace Zorg.Imaging.Drawing;
/// beyond a million pixels are clamped.
///
///
-/// The canvas is new and may still change, or move to its own package: using it needs the diagnostic
-/// ZORGDRAW suppressed. It isn't safe to use from several threads at once.
+/// It isn't safe to use from several threads at once.
///
///
///
@@ -36,12 +35,8 @@ namespace Zorg.Imaging.Drawing;
/// page.SaveAsPng(output);
///
///
-[Experimental(Diagnostic)]
public sealed class Canvas : IDisposable
{
- /// The diagnostic that marks the drawing API as new.
- internal const string Diagnostic = "ZORGDRAW";
-
private readonly Rasterizer _rasterizer = new();
private Matrix3x2 _transform = Matrix3x2.Identity;
private float _tolerance = 0.2f;
diff --git a/src/Zorg.Imaging/Drawing/FillRule.cs b/src/Zorg.Imaging/Drawing/FillRule.cs
index dcf10db..f91dd4b 100644
--- a/src/Zorg.Imaging/Drawing/FillRule.cs
+++ b/src/Zorg.Imaging/Drawing/FillRule.cs
@@ -1,10 +1,7 @@
-using System.Diagnostics.CodeAnalysis;
-
namespace Zorg.Imaging.Drawing;
/// Which points a shape whose outline crosses itself, or has holes, covers.
/// canvas.Fill(ring, black, FillRule.EvenOdd);
-[Experimental(Canvas.Diagnostic)]
public enum FillRule
{
///
diff --git a/src/Zorg.Imaging/Drawing/Shape.cs b/src/Zorg.Imaging/Drawing/Shape.cs
index a0cec50..cd5d8a7 100644
--- a/src/Zorg.Imaging/Drawing/Shape.cs
+++ b/src/Zorg.Imaging/Drawing/Shape.cs
@@ -1,5 +1,4 @@
using System;
-using System.Diagnostics.CodeAnalysis;
namespace Zorg.Imaging.Drawing;
@@ -17,7 +16,6 @@ namespace Zorg.Imaging.Drawing;
/// canvas.Fill(triangle, new Rgba32(200, 0, 0));
///
///
-[Experimental(Canvas.Diagnostic)]
public sealed class Shape
{
internal const byte Move = 0;
diff --git a/src/Zorg.Imaging/Image.Cmyk.cs b/src/Zorg.Imaging/Image.Cmyk.cs
new file mode 100644
index 0000000..c9a70d2
--- /dev/null
+++ b/src/Zorg.Imaging/Image.Cmyk.cs
@@ -0,0 +1,265 @@
+using System;
+using Zorg.Imaging.Processing;
+
+namespace Zorg.Imaging;
+
+/// Decoding CMYK files as their inks.
+public sealed partial class Image
+{
+ ///
+ /// Decodes a CMYK file (a four-component JPEG, including YCCK, or a separated TIFF) as its inks instead of
+ /// converting it to sRGB: for print work, such as a PDF that keeps DeviceCMYK.
+ /// converts the same file to sRGB.
+ ///
+ /// The whole file. It isn't copied, so don't change it while decoding.
+ ///
+ /// The limits and options, or for . Orientation and
+ /// apply as for ;
+ /// doesn't, as each ink is an plane.
+ ///
+ /// The inks, which the caller disposes, or when the file is an image but not CMYK.
+ /// The data isn't an image format this version can decode.
+ /// The file is damaged or ends early.
+ /// The image is larger than allows.
+ ///
+ ///
+ /// using CmykImage? inks = Image.DecodeCmyk(jpeg, new DecodeOptions { ShrinkTo = (1200, 1200) });
+ /// if (inks is not null)
+ /// {
+ /// using CmykImage fitted = inks.Map(plane => plane.Fit(1200, 1200));
+ /// byte[] deviceCmyk = fitted.ToInterleaved(); // C, M, Y, K per pixel, as a PDF image stream holds them
+ /// }
+ ///
+ ///
+ public static CmykImage? DecodeCmyk(ReadOnlyMemory data, DecodeOptions? options = null)
+ {
+ options ??= DecodeOptions.Default;
+
+ // The header says whether the file is CMYK, so other images aren't decoded only to be thrown away. A file
+ // Identify can't read goes on to Decode, which throws the exception that says why.
+ if (Identify(data) is { Succeeded: true, Info.IsCmyk: false })
+ {
+ return null;
+ }
+
+ Image decoded = Decode(data, options.WithInks());
+ try
+ {
+ if (decoded.InkProfile is not { } profile)
+ {
+ return null;
+ }
+
+ return CmykImage.Split(decoded, profile);
+ }
+ finally
+ {
+ decoded.Dispose();
+ }
+ }
+}
+
+///
+/// A CMYK picture as its four inks: cyan, magenta, yellow and black planes, each an image
+/// from 0 (no ink) to 255 (full ink), with the file's CMYK colour profile. From .
+///
+///
+/// The planes are ordinary images in , so can resize, crop, turn and
+/// flip them with the usual operations, and resizing blends ink amounts directly, as print software does, without the
+/// gamma that sRGB values would get. gives the bytes a PDF DeviceCMYK image holds;
+/// a picture for the screen.
+///
+public sealed class CmykImage : IDisposable
+{
+ private readonly byte[] _profile;
+
+ private CmykImage(Image cyan, Image magenta, Image yellow, Image black, byte[] profile)
+ {
+ (Cyan, Magenta, Yellow, Black, _profile) = (cyan, magenta, yellow, black, profile);
+ }
+
+ /// The cyan ink, 0 (none) to 255 (full).
+ public Image Cyan { get; }
+
+ /// The magenta ink, 0 (none) to 255 (full).
+ public Image Magenta { get; }
+
+ /// The yellow ink, 0 (none) to 255 (full).
+ public Image Yellow { get; }
+
+ /// The black ink, 0 (none) to 255 (full).
+ public Image Black { get; }
+
+ /// The width in pixels.
+ public int Width => Cyan.Width;
+
+ /// The height in pixels.
+ public int Height => Cyan.Height;
+
+ /// The file's CMYK ICC profile, or empty when it has none (the inks are then device CMYK).
+ public ReadOnlyMemory IccProfile => _profile;
+
+ /// Applies the same operation to each ink, such as plane => plane.Fit(1200, 1200).
+ /// An operation from one image to a new one; it's called four times.
+ /// New inks, which the caller disposes; these are unchanged.
+ /// is .
+ /// The operation returned the same image, another layout, or planes of different sizes.
+ /// using CmykImage turned = inks.Map(plane => plane.Rotate(90));
+ public CmykImage Map(Func operation)
+ {
+ ArgumentNullException.ThrowIfNull(operation);
+ Image[] planes = new Image[4];
+ try
+ {
+ Image[] inputs = [Cyan, Magenta, Yellow, Black];
+ for (int i = 0; i < 4; i++)
+ {
+ Image result = operation(inputs[i]);
+ if (Array.IndexOf(inputs, result) >= 0)
+ {
+ throw new InvalidOperationException("The operation must return a new image, not the one it was given.");
+ }
+
+ planes[i] = result;
+ if (result is null || result.PixelFormat != PixelFormat.L8 || result.Width != planes[0].Width || result.Height != planes[0].Height)
+ {
+ throw new InvalidOperationException("The operation must give every ink an L8 image of the same size.");
+ }
+
+ result.ColorSpace = ColorSpace.LinearSrgb;
+ }
+
+ var mapped = new CmykImage(planes[0], planes[1], planes[2], planes[3], _profile);
+ planes = [];
+ return mapped;
+ }
+ finally
+ {
+ foreach (Image? plane in planes)
+ {
+ plane?.Dispose();
+ }
+ }
+ }
+
+ /// The inks interleaved: C, M, Y, K for each pixel, row by row, 0 no ink to 255 full, as a PDF DeviceCMYK image holds them.
+ /// A new array of × × 4 bytes.
+ /// The picture is too large for one array.
+ /// The inks have been disposed.
+ /// byte[] deviceCmyk = inks.ToInterleaved();
+ public byte[] ToInterleaved()
+ {
+ long size = (long)Width * Height * 4;
+ if (size > Array.MaxLength)
+ {
+ throw new InvalidOperationException($"{Width} x {Height} CMYK is more than one array can hold.");
+ }
+
+ byte[] result = new byte[size];
+ int width = Width;
+ Rows(width, Height, (top, bottom) =>
+ {
+ for (int y = top; y < bottom; y++)
+ {
+ ReadOnlySpan c = Cyan.GetRowBytes(y), m = Magenta.GetRowBytes(y), ye = Yellow.GetRowBytes(y), k = Black.GetRowBytes(y);
+ Span row = result.AsSpan(y * width * 4, width * 4);
+ for (int x = 0; x < width; x++)
+ {
+ (row[4 * x], row[(4 * x) + 1], row[(4 * x) + 2], row[(4 * x) + 3]) = (c[x], m[x], ye[x], k[x]);
+ }
+ }
+ });
+ return result;
+ }
+
+ ///
+ /// The picture in sRGB, for the screen: through the CMYK profile when there is one, else by the device formula, as
+ /// converts the file.
+ ///
+ /// A new image, which the caller disposes.
+ /// The inks have been disposed.
+ /// using Image preview = inks.ToSrgb();
+ public Image ToSrgb()
+ {
+ var convert = Codecs.Jpeg.JpegCmyk.For(-1, _profile);
+ var result = new Image(Width, Height, PixelFormat.Rgb24);
+ try
+ {
+ int width = Width;
+ Rows(width, Height, (top, bottom) =>
+ {
+ byte[][] rows = [new byte[width], new byte[width], new byte[width], new byte[width]];
+ for (int y = top; y < bottom; y++)
+ {
+ Cyan.GetRowBytes(y).CopyTo(rows[0]);
+ Magenta.GetRowBytes(y).CopyTo(rows[1]);
+ Yellow.GetRowBytes(y).CopyTo(rows[2]);
+ Black.GetRowBytes(y).CopyTo(rows[3]);
+ convert.WriteRow(rows, result.GetRowBytes(y), PixelFormat.Rgb24, width);
+ }
+ });
+ return result;
+ }
+ catch
+ {
+ result.Dispose();
+ throw;
+ }
+ }
+
+ /// Returns the planes' memory to the pool.
+ /// inks.Dispose();
+ public void Dispose()
+ {
+ Cyan.Dispose();
+ Magenta.Dispose();
+ Yellow.Dispose();
+ Black.Dispose();
+ }
+
+ /// Runs over bands of rows, in parallel for large pictures.
+ private static void Rows(int width, int height, Action body)
+ {
+ int bands = Parallelism.Bands((long)width * height, height / 16);
+ Parallelism.For(bands, band => body((int)((long)height * band / bands), (int)((long)height * (band + 1) / bands)));
+ }
+
+ /// Splits a decoder's interleaved inks (C, M, Y, K in the four bytes of an Rgba32 image) into planes.
+ internal static CmykImage Split(Image inks, byte[] profile)
+ {
+ int width = inks.Width, height = inks.Height;
+ Image[] planes = new Image[4];
+ try
+ {
+ for (int i = 0; i < 4; i++)
+ {
+ planes[i] = new Image(width, height, PixelFormat.L8) { ColorSpace = ColorSpace.LinearSrgb };
+ }
+
+ Image[] p = planes;
+ Rows(width, height, (top, bottom) =>
+ {
+ for (int y = top; y < bottom; y++)
+ {
+ ReadOnlySpan source = inks.GetRowBytes(y);
+ Span c = p[0].GetRowBytes(y), m = p[1].GetRowBytes(y), ye = p[2].GetRowBytes(y), k = p[3].GetRowBytes(y);
+ for (int x = 0; x < width; x++)
+ {
+ (c[x], m[x], ye[x], k[x]) = (source[4 * x], source[(4 * x) + 1], source[(4 * x) + 2], source[(4 * x) + 3]);
+ }
+ }
+ });
+
+ var result = new CmykImage(planes[0], planes[1], planes[2], planes[3], profile);
+ planes = [];
+ return result;
+ }
+ finally
+ {
+ foreach (Image? plane in planes)
+ {
+ plane?.Dispose();
+ }
+ }
+ }
+}
diff --git a/src/Zorg.Imaging/Image.Pixels.cs b/src/Zorg.Imaging/Image.Pixels.cs
index 00d915e..1d30e4a 100644
--- a/src/Zorg.Imaging/Image.Pixels.cs
+++ b/src/Zorg.Imaging/Image.Pixels.cs
@@ -77,6 +77,13 @@ public ColorSpace ColorSpace
/// The metadata from the file this image was decoded from, carried by operations, for the encoders.
internal Metadata.SourceMetadata? SourceMetadata { get; set; }
+ ///
+ /// Set when the decoder kept a CMYK file's inks (): the pixels are C, M, Y and K
+ /// in the four bytes of each pixel, and this is the file's CMYK ICC profile, empty
+ /// when it has none.
+ ///
+ internal byte[]? InkProfile { get; set; }
+
///
/// The metadata the image was decoded with (EXIF, XMP and IPTC, and the facts most wanted from them), or
/// when the file had none or the image was made in code. Operations carry it to the images
diff --git a/src/Zorg.Imaging/ImageInfo.cs b/src/Zorg.Imaging/ImageInfo.cs
index bd74077..d3903aa 100644
--- a/src/Zorg.Imaging/ImageInfo.cs
+++ b/src/Zorg.Imaging/ImageInfo.cs
@@ -92,6 +92,9 @@ public ImageInfo(ImageFormat format, int width, int height)
/// bool exif = info.HasExif;
public bool HasExif { get; init; }
+ /// Whether the pixels are CMYK ink (a four-component JPEG or a separated TIFF), for .
+ internal bool IsCmyk { get; init; }
+
private bool SwapsAxes => Orientation is >= 5 and <= 8;
/// Returns the format and display size, such as JPEG 3024x4032.
diff --git a/src/Zorg.Imaging/PublicAPI.Shipped.txt b/src/Zorg.Imaging/PublicAPI.Shipped.txt
index 7cb9471..f077aec 100644
--- a/src/Zorg.Imaging/PublicAPI.Shipped.txt
+++ b/src/Zorg.Imaging/PublicAPI.Shipped.txt
@@ -544,39 +544,39 @@ Zorg.Imaging.DecodeOptions.ShrinkTo.get -> (int Width, int Height)?
Zorg.Imaging.DecodeOptions.ShrinkTo.init -> void
Zorg.Imaging.Image.Convert(Zorg.Imaging.PixelFormat format) -> Zorg.Imaging.Image!
Zorg.Imaging.Image.IsOpaque() -> bool
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Canvas(Zorg.Imaging.Image! image) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Clear(Zorg.Imaging.Rgba32 color) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Dispose() -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Fill(Zorg.Imaging.Drawing.Shape! shape, Zorg.Imaging.Rgba32 color, Zorg.Imaging.Drawing.FillRule rule = Zorg.Imaging.Drawing.FillRule.NonZero) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Fill(Zorg.Imaging.Drawing.Shape! shape, Zorg.Imaging.Rgba32 color, in System.Numerics.Matrix3x2 transform, Zorg.Imaging.Drawing.FillRule rule = Zorg.Imaging.Drawing.FillRule.NonZero) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.FillRectangle(float x, float y, float width, float height, Zorg.Imaging.Rgba32 color) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Image.get -> Zorg.Imaging.Image!
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.ResetClip() -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.SetClip(int x, int y, int width, int height) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Tolerance.get -> float
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Tolerance.set -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Transform.get -> System.Numerics.Matrix3x2
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Transform.set -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.FillRule
-[ZORGDRAW]Zorg.Imaging.Drawing.FillRule.EvenOdd = 1 -> Zorg.Imaging.Drawing.FillRule
-[ZORGDRAW]Zorg.Imaging.Drawing.FillRule.NonZero = 0 -> Zorg.Imaging.Drawing.FillRule
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.Clear() -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.Close() -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.CubicTo(float control1X, float control1Y, float control2X, float control2Y, float x, float y) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.IsEmpty.get -> bool
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.LineTo(float x, float y) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.MoveTo(float x, float y) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.QuadTo(float controlX, float controlY, float x, float y) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.SegmentCount.get -> int
-[ZORGDRAW]Zorg.Imaging.Drawing.Shape.Shape() -> void
-[ZORGDRAW]static Zorg.Imaging.Drawing.Shape.Ellipse(float centerX, float centerY, float radiusX, float radiusY) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]static Zorg.Imaging.Drawing.Shape.Rectangle(float x, float y, float width, float height) -> Zorg.Imaging.Drawing.Shape!
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.MinimumStrokeWidth.get -> float
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.MinimumStrokeWidth.set -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Stroke(Zorg.Imaging.Drawing.Shape! shape, float width, Zorg.Imaging.Rgba32 color) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.Stroke(Zorg.Imaging.Drawing.Shape! shape, float width, Zorg.Imaging.Rgba32 color, in System.Numerics.Matrix3x2 transform) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.StrokeLine(float x1, float y1, float x2, float y2, float width, Zorg.Imaging.Rgba32 color) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.DrawImage(Zorg.Imaging.Image! image, float x, float y, float width, float height, Zorg.Imaging.Resampler? resampler = null, double opacity = 1) -> void
-[ZORGDRAW]Zorg.Imaging.Drawing.Canvas.DrawImage(Zorg.Imaging.Image! image, in System.Numerics.Matrix3x2 transform, Zorg.Imaging.Resampler? resampler = null, double opacity = 1) -> void
+Zorg.Imaging.Drawing.Canvas
+Zorg.Imaging.Drawing.Canvas.Canvas(Zorg.Imaging.Image! image) -> void
+Zorg.Imaging.Drawing.Canvas.Clear(Zorg.Imaging.Rgba32 color) -> void
+Zorg.Imaging.Drawing.Canvas.Dispose() -> void
+Zorg.Imaging.Drawing.Canvas.Fill(Zorg.Imaging.Drawing.Shape! shape, Zorg.Imaging.Rgba32 color, Zorg.Imaging.Drawing.FillRule rule = Zorg.Imaging.Drawing.FillRule.NonZero) -> void
+Zorg.Imaging.Drawing.Canvas.Fill(Zorg.Imaging.Drawing.Shape! shape, Zorg.Imaging.Rgba32 color, in System.Numerics.Matrix3x2 transform, Zorg.Imaging.Drawing.FillRule rule = Zorg.Imaging.Drawing.FillRule.NonZero) -> void
+Zorg.Imaging.Drawing.Canvas.FillRectangle(float x, float y, float width, float height, Zorg.Imaging.Rgba32 color) -> void
+Zorg.Imaging.Drawing.Canvas.Image.get -> Zorg.Imaging.Image!
+Zorg.Imaging.Drawing.Canvas.ResetClip() -> void
+Zorg.Imaging.Drawing.Canvas.SetClip(int x, int y, int width, int height) -> void
+Zorg.Imaging.Drawing.Canvas.Tolerance.get -> float
+Zorg.Imaging.Drawing.Canvas.Tolerance.set -> void
+Zorg.Imaging.Drawing.Canvas.Transform.get -> System.Numerics.Matrix3x2
+Zorg.Imaging.Drawing.Canvas.Transform.set -> void
+Zorg.Imaging.Drawing.FillRule
+Zorg.Imaging.Drawing.FillRule.EvenOdd = 1 -> Zorg.Imaging.Drawing.FillRule
+Zorg.Imaging.Drawing.FillRule.NonZero = 0 -> Zorg.Imaging.Drawing.FillRule
+Zorg.Imaging.Drawing.Shape
+Zorg.Imaging.Drawing.Shape.Clear() -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.Close() -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.CubicTo(float control1X, float control1Y, float control2X, float control2Y, float x, float y) -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.IsEmpty.get -> bool
+Zorg.Imaging.Drawing.Shape.LineTo(float x, float y) -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.MoveTo(float x, float y) -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.QuadTo(float controlX, float controlY, float x, float y) -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Shape.SegmentCount.get -> int
+Zorg.Imaging.Drawing.Shape.Shape() -> void
+static Zorg.Imaging.Drawing.Shape.Ellipse(float centerX, float centerY, float radiusX, float radiusY) -> Zorg.Imaging.Drawing.Shape!
+static Zorg.Imaging.Drawing.Shape.Rectangle(float x, float y, float width, float height) -> Zorg.Imaging.Drawing.Shape!
+Zorg.Imaging.Drawing.Canvas.MinimumStrokeWidth.get -> float
+Zorg.Imaging.Drawing.Canvas.MinimumStrokeWidth.set -> void
+Zorg.Imaging.Drawing.Canvas.Stroke(Zorg.Imaging.Drawing.Shape! shape, float width, Zorg.Imaging.Rgba32 color) -> void
+Zorg.Imaging.Drawing.Canvas.Stroke(Zorg.Imaging.Drawing.Shape! shape, float width, Zorg.Imaging.Rgba32 color, in System.Numerics.Matrix3x2 transform) -> void
+Zorg.Imaging.Drawing.Canvas.StrokeLine(float x1, float y1, float x2, float y2, float width, Zorg.Imaging.Rgba32 color) -> void
+Zorg.Imaging.Drawing.Canvas.DrawImage(Zorg.Imaging.Image! image, float x, float y, float width, float height, Zorg.Imaging.Resampler? resampler = null, double opacity = 1) -> void
+Zorg.Imaging.Drawing.Canvas.DrawImage(Zorg.Imaging.Image! image, in System.Numerics.Matrix3x2 transform, Zorg.Imaging.Resampler? resampler = null, double opacity = 1) -> void
diff --git a/src/Zorg.Imaging/PublicAPI.Unshipped.txt b/src/Zorg.Imaging/PublicAPI.Unshipped.txt
index 7dc5c58..0b847f5 100644
--- a/src/Zorg.Imaging/PublicAPI.Unshipped.txt
+++ b/src/Zorg.Imaging/PublicAPI.Unshipped.txt
@@ -1 +1,14 @@
#nullable enable
+Zorg.Imaging.CmykImage
+Zorg.Imaging.CmykImage.Black.get -> Zorg.Imaging.Image!
+Zorg.Imaging.CmykImage.Cyan.get -> Zorg.Imaging.Image!
+Zorg.Imaging.CmykImage.Dispose() -> void
+Zorg.Imaging.CmykImage.Height.get -> int
+Zorg.Imaging.CmykImage.IccProfile.get -> System.ReadOnlyMemory
+Zorg.Imaging.CmykImage.Magenta.get -> Zorg.Imaging.Image!
+Zorg.Imaging.CmykImage.Map(System.Func! operation) -> Zorg.Imaging.CmykImage!
+Zorg.Imaging.CmykImage.ToInterleaved() -> byte[]!
+Zorg.Imaging.CmykImage.ToSrgb() -> Zorg.Imaging.Image!
+Zorg.Imaging.CmykImage.Width.get -> int
+Zorg.Imaging.CmykImage.Yellow.get -> Zorg.Imaging.Image!
+static Zorg.Imaging.Image.DecodeCmyk(System.ReadOnlyMemory data, Zorg.Imaging.DecodeOptions? options = null) -> Zorg.Imaging.CmykImage?
diff --git a/src/Zorg.Imaging/Zorg.Imaging.csproj b/src/Zorg.Imaging/Zorg.Imaging.csproj
index 5eeedb6..024a70a 100644
--- a/src/Zorg.Imaging/Zorg.Imaging.csproj
+++ b/src/Zorg.Imaging/Zorg.Imaging.csproj
@@ -3,8 +3,6 @@
Managed image decoding, resizing and encoding for .NET: PNG, JPEG, GIF and WebP, including animations, plus BMP and TIFF decoding, with no native dependencies.
image;imaging;resize;thumbnail;png;jpeg;gif;webp;exif
-
- $(NoWarn);ZORGDRAW
diff --git a/tests/Zorg.Imaging.Tests/CmykDecodeTests.cs b/tests/Zorg.Imaging.Tests/CmykDecodeTests.cs
new file mode 100644
index 0000000..ed85a6b
--- /dev/null
+++ b/tests/Zorg.Imaging.Tests/CmykDecodeTests.cs
@@ -0,0 +1,185 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using Xunit;
+using Zorg.Imaging.Codecs.Jpeg;
+using Zorg.Imaging.Tests.Codecs.Png;
+using Zorg.Imaging.Tests.Codecs.Tiff;
+using Zorg.Imaging.Tests.Metadata;
+using static Zorg.Imaging.Tests.Codecs.Jpeg.JpegTestFiles;
+
+namespace Zorg.Imaging.Tests;
+
+/// : a CMYK file's inks, as planes, instead of sRGB.
+public class CmykDecodeTests
+{
+ [Theory]
+ [InlineData("ycck")]
+ [InlineData("ycck-subsampled")]
+ public void The_inks_convert_to_what_Decode_gives(string name)
+ {
+ byte[] jpeg = Sample(name);
+ using CmykImage? inks = Image.DecodeCmyk(jpeg);
+ Assert.NotNull(inks);
+ using Image decoded = Image.Decode(jpeg);
+ Assert.Equal((decoded.Width, decoded.Height), (inks.Width, inks.Height));
+ foreach (Image plane in new[] { inks.Cyan, inks.Magenta, inks.Yellow, inks.Black })
+ {
+ Assert.Equal(PixelFormat.L8, plane.PixelFormat);
+ Assert.Same(ColorSpace.LinearSrgb, plane.ColorSpace);
+ }
+
+ using Image srgb = inks.ToSrgb();
+ Assert.Equal(decoded.GetPixelBytes().ToArray(), srgb.GetPixelBytes().ToArray());
+ Assert.True(inks.IccProfile.IsEmpty);
+ }
+
+ [Fact]
+ public void The_planes_hold_each_pixel_s_inks()
+ {
+ // The YCCK samples, decoded as RGB, are the C, M, Y inks; the check is the device formula on the planes.
+ using CmykImage inks = Image.DecodeCmyk(Sample("ycck"))!;
+ byte[] interleaved = inks.ToInterleaved();
+ Assert.Equal(inks.Width * inks.Height * 4, interleaved.Length);
+ using Image decoded = Image.Decode(Sample("ycck"));
+ for (int y = 0; y < inks.Height; y += 7)
+ {
+ for (int x = 0; x < inks.Width; x += 5)
+ {
+ int at = ((y * inks.Width) + x) * 4;
+ (byte c, byte m, byte ye, byte k) = (interleaved[at], interleaved[at + 1], interleaved[at + 2], interleaved[at + 3]);
+ Assert.Equal((c, m, ye, k), (inks.Cyan.GetRowBytes(y)[x], inks.Magenta.GetRowBytes(y)[x], inks.Yellow.GetRowBytes(y)[x], inks.Black.GetRowBytes(y)[x]));
+ Rgb24 p = decoded.GetRow(y)[x];
+ Assert.Equal(JpegCmyk.Device(c, m, ye, k), (p.R, p.G, p.B));
+ }
+ }
+ }
+
+ [Fact]
+ public void Files_that_aren_t_cmyk_give_null_and_non_images_throw()
+ {
+ Assert.Null(Image.DecodeCmyk(Sample("s420")));
+ using Image small = new(3, 2, PixelFormat.Rgb24);
+ Assert.Null(Image.DecodeCmyk(PngEncoderTests.Save(small)));
+ Assert.Throws(() => Image.DecodeCmyk(new byte[] { 1, 2, 3, 4 }));
+ Assert.Throws(() => Image.DecodeCmyk(Sample("ycck").AsMemory(0, 400)));
+ }
+
+ [Fact]
+ public void Shrink_on_load_and_orientation_apply_as_for_Decode()
+ {
+ byte[] jpeg = Sample("ycck-subsampled");
+ var options = new DecodeOptions { ShrinkTo = (17, 12) };
+ using CmykImage shrunk = Image.DecodeCmyk(jpeg, options)!;
+ using Image decoded = Image.Decode(jpeg, options);
+ Assert.Equal((decoded.Width, decoded.Height), (shrunk.Width, shrunk.Height));
+ Assert.True(shrunk.Width < 67);
+ using (Image srgb = shrunk.ToSrgb())
+ {
+ Assert.Equal(decoded.GetPixelBytes().ToArray(), srgb.GetPixelBytes().ToArray());
+ }
+
+ // Orientation 6: the planes come out turned a quarter clockwise, as the decoded picture does.
+ byte[] turned = WithSegments(jpeg, (0xE1, [.. "Exif\0\0"u8, .. PngTestFiles.ExifWithOrientation(6)]));
+ using CmykImage upright = Image.DecodeCmyk(turned)!;
+ using CmykImage stored = Image.DecodeCmyk(turned, new DecodeOptions { ApplyOrientation = false })!;
+ using CmykImage rotated = stored.Map(plane => plane.Rotate(90));
+ Assert.Equal((45, 67), (upright.Width, upright.Height));
+ Assert.Equal(rotated.ToInterleaved(), upright.ToInterleaved());
+ }
+
+ [Fact]
+ public void A_cmyk_profile_is_kept_and_used_for_the_screen()
+ {
+ byte[] profile = IccTestProfiles.NaiveCmyk(IccTestProfiles.TagType.Lut16, points: 17);
+ byte[] jpeg = WithIcc(Sample("ycck"), profile);
+ using CmykImage inks = Image.DecodeCmyk(jpeg)!;
+ Assert.Equal(profile, inks.IccProfile.ToArray());
+ using Image decoded = Image.Decode(jpeg);
+ using Image srgb = inks.ToSrgb();
+ Assert.Equal(decoded.GetPixelBytes().ToArray(), srgb.GetPixelBytes().ToArray());
+ }
+
+ [Fact]
+ public void Map_resizes_every_ink_and_refuses_what_doesn_t_fit()
+ {
+ using CmykImage inks = Image.DecodeCmyk(Sample("ycck"))!;
+ using CmykImage half = inks.Map(plane => plane.Fit(34, 34));
+ Assert.Equal((34, 23), (half.Width, half.Height));
+ Assert.Equal(inks.IccProfile.Length, half.IccProfile.Length);
+
+ // Ink blends as an amount: a fit of flat ink keeps the amount (no gamma, which would shift it).
+ using CmykImage flat = inks.Map(plane =>
+ {
+ var image = new Image(40, 40, PixelFormat.L8);
+ image.GetPixelBytes().Fill(100);
+ return image;
+ });
+ using CmykImage small = flat.Map(plane => plane.Fit(13, 13));
+ Assert.All(small.ToInterleaved(), b => Assert.Equal(100, b));
+
+ Assert.Throws(() => inks.Map(null!));
+ Assert.Throws(() => inks.Map(plane => plane));
+ Assert.Throws(() => inks.Map(plane => plane.Convert(PixelFormat.Rgb24)));
+ int calls = 0;
+ Assert.Throws(() => inks.Map(plane => plane.Fit(20 + calls++, 20 + calls)));
+ }
+
+ [Fact]
+ public void A_separated_tiff_gives_its_inks()
+ {
+ byte[] samples = new byte[5 * 3 * 4];
+ new Random(4).NextBytes(samples);
+ byte[] tiff = TiffDecoderTests.Tiff(5, 3, bits: 8, samples: 4, photometric: 5, strips: [samples], rowsPerStrip: 3);
+ using CmykImage inks = Image.DecodeCmyk(tiff)!;
+ Assert.Equal(samples, inks.ToInterleaved());
+ using Image decoded = Image.Decode(tiff);
+ using Image srgb = inks.ToSrgb();
+ using Image decodedRgb = decoded.Convert(PixelFormat.Rgb24);
+ Assert.Equal(decodedRgb.GetPixelBytes().ToArray(), srgb.GetPixelBytes().ToArray());
+ }
+
+ [Fact]
+ public void Disposing_returns_every_plane()
+ {
+ CmykImage inks = Image.DecodeCmyk(Sample("ycck"))!;
+ inks.Dispose();
+ Assert.Throws(() => inks.Cyan.GetPixelBytes());
+ Assert.Throws(() => inks.Black.GetPixelBytes());
+ Assert.Throws(() => inks.ToInterleaved());
+ }
+
+ [Fact]
+ public async Task The_inks_match_ImageMagick_s()
+ {
+ // ImageMagick writes a plain (Adobe-marked) CMYK JPEG and reads back its raw inks: ours must be the same.
+ string magick = Oracle.Require("magick");
+ using Oracle.TempFolder folder = Oracle.CreateFolder();
+ using Image source = PngEncoderTests.Smooth(48, 32, PixelFormat.Rgb24, seed: 6);
+ await File.WriteAllBytesAsync(folder.File("in.png"), PngEncoderTests.Save(source), TestContext.Current.CancellationToken);
+ (int code, _, string errors) = await Oracle.RunAsync(magick, folder.File("in.png"), "-colorspace", "CMYK", "-quality", "95", folder.File("cmyk.jpg"));
+ Assert.True(code == 0, errors);
+ (code, byte[] raw, errors) = await Oracle.RunAsync(magick, folder.File("cmyk.jpg"), "-depth", "8", "cmyk:-");
+ Assert.True(code == 0, errors);
+
+ using CmykImage inks = Image.DecodeCmyk(await File.ReadAllBytesAsync(folder.File("cmyk.jpg"), TestContext.Current.CancellationToken))!;
+ Assert.NotNull(inks);
+ (int max, double mean) = Compare(inks.ToInterleaved(), raw);
+ Assert.True(max <= 1 && mean < 0.1, $"largest {max}, mean {mean:0.###}");
+ }
+
+ // The file with the profile in APP2 chunks of at most 65,519 bytes, after SOI.
+ private static byte[] WithIcc(byte[] jpeg, byte[] profile)
+ {
+ const int Chunk = 65519;
+ int count = (profile.Length + Chunk - 1) / Chunk;
+ var segments = new (int, byte[])[count];
+ for (int i = 0; i < count; i++)
+ {
+ byte[] part = profile.AsSpan(i * Chunk, Math.Min(Chunk, profile.Length - (i * Chunk))).ToArray();
+ segments[i] = (0xE2, [.. "ICC_PROFILE\0"u8, (byte)(i + 1), (byte)count, .. part]);
+ }
+
+ return WithSegments(jpeg, segments);
+ }
+}
diff --git a/tests/Zorg.Imaging.Tests/Zorg.Imaging.Tests.csproj b/tests/Zorg.Imaging.Tests/Zorg.Imaging.Tests.csproj
index 0cb5576..1f2cdfd 100644
--- a/tests/Zorg.Imaging.Tests/Zorg.Imaging.Tests.csproj
+++ b/tests/Zorg.Imaging.Tests/Zorg.Imaging.Tests.csproj
@@ -2,8 +2,6 @@
Exe
-
- $(NoWarn);ZORGDRAW