Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<!-- The canvas is marked experimental; the benchmarks time it anyway. -->
<NoWarn>$(NoWarn);ZORGDRAW</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
31 changes: 31 additions & 0 deletions docs/cmyk.md
Original file line number Diff line number Diff line change
@@ -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<byte> 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.
7 changes: 1 addition & 6 deletions docs/drawing.md
Original file line number Diff line number Diff line change
@@ -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>$(NoWarn);ZORGDRAW</NoWarn>
```
previews of pages (PDF), charts and badges.

```csharp
using System.Numerics;
Expand Down
2 changes: 0 additions & 2 deletions samples/Zorg.Imaging.AotSmoke/Zorg.Imaging.AotSmoke.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
<!-- Report each trim and AOT warning, not one summary warning per assembly. -->
<TrimmerSingleWarn>false</TrimmerSingleWarn>
<InvariantGlobalization>true</InvariantGlobalization>
<!-- The canvas is marked experimental; the smoke test exercises it anyway. -->
<NoWarn>$(NoWarn);ZORGDRAW</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
28 changes: 22 additions & 6 deletions src/Zorg.Imaging/Codecs/Jpeg/JpegCmyk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </para>
/// <para>
/// 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
/// <see cref="Image.DecodeCmyk"/> it is the inks themselves, in the four bytes of each pixel.
/// </para>
/// </remarks>
internal sealed class JpegCmyk
Expand All @@ -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;
}

/// <summary>Whether <see cref="WriteRow"/> writes the inks themselves, C, M, Y, K in four bytes, instead of sRGB.</summary>
public bool KeepInks { get; }

/// <summary>How the four components hold the inks.</summary>
public enum Storage
{
Expand All @@ -46,7 +51,7 @@ public enum Storage
}

/// <summary>The conversion for a file's Adobe transform (-1 when it has no Adobe marker) and its ICC profile.</summary>
public static JpegCmyk For(int adobeTransform, ReadOnlySpan<byte> profile)
public static JpegCmyk For(int adobeTransform, ReadOnlySpan<byte> profile, bool keepInks = false)
{
Storage storage = adobeTransform switch
{
Expand All @@ -56,12 +61,12 @@ public static JpegCmyk For(int adobeTransform, ReadOnlySpan<byte> 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);
}

/// <summary>Whether a profile does the conversion (otherwise the device formula).</summary>
Expand All @@ -70,6 +75,17 @@ public static JpegCmyk For(int adobeTransform, ReadOnlySpan<byte> profile)
/// <summary>Writes one row: four planes' samples in, pixels in <paramref name="format"/> out.</summary>
public void WriteRow(byte[][] rows, Span<byte> 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<float> device = stackalloc float[4];
for (int x = 0; x < width; x++)
{
Expand Down
8 changes: 6 additions & 2 deletions src/Zorg.Imaging/Codecs/Jpeg/JpegDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/Zorg.Imaging/Codecs/Jpeg/JpegHeaderReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ public static async ValueTask<ImageInfo> ReadAsync(HeaderReader reader, Identify
HasExif = hasExif,
HasIccProfile = hasIcc,
ColorSpace = colorSpace,
IsCmyk = scratch[5] == 4,
};
}

Expand Down
3 changes: 2 additions & 1 deletion src/Zorg.Imaging/Codecs/Jpeg/JpegOutput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
30 changes: 30 additions & 0 deletions src/Zorg.Imaging/Codecs/Tiff/TiffDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public static async ValueTask<Image> DecodeAsync(DataReader reader, DecodeOption
ReadOnlyMemory<byte> 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
Expand All @@ -49,6 +50,7 @@ public static async ValueTask<Image> DecodeAsync(DataReader reader, DecodeOption
}
}

image.InkProfile = inks ? directory.IccProfile ?? [] : null;
return image;
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -398,6 +405,29 @@ private static Image ToImage(byte[] pixels, TiffDirectory d, DecodeOptions optio
return result;
}

/// <summary>A separated (CMYK) TIFF's inks as they are, C, M, Y and K in four bytes, 0 no ink to 255 full.</summary>
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<byte> source = pixels.AsSpan((int)((long)y * width * samples * sampleBytes), width * samples * sampleBytes);
Span<byte> 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<byte> row, int samples, bool sixteen, int x, int s) =>
sixteen ? MemoryMarshal.Read<ushort>(row[(((x * samples) + s) * 2)..]) : row[(x * samples) + s];

Expand Down
1 change: 1 addition & 0 deletions src/Zorg.Imaging/Codecs/Tiff/TiffHeaderReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public static async ValueTask<ImageInfo> ReadAsync(HeaderReader reader, Identify
HasIccProfile = icc,
HasExif = exif,
ColorSpace = options.ReadColorSpace && !icc ? ColorSpace.Srgb : null,
IsCmyk = photometric == 5,
};
}
}
18 changes: 18 additions & 0 deletions src/Zorg.Imaging/DecodeOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,23 @@ public int MaxDegreeOfParallelism

private readonly Func<int, int, (int Width, int Height)>? _shrinkToTarget;

/// <summary>
/// For <see cref="Image.DecodeCmyk"/>: a CMYK file's pixels come out as its inks, C, M, Y and K in the four bytes of
/// an <see cref="PixelFormat.Rgba32"/> image, 0 no ink to 255 full, with <see cref="Image.InkProfile"/> set.
/// </summary>
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<int, int, (int Width, int Height)>? target) => new()
{
Limits = Limits,
Expand All @@ -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,
};
}
7 changes: 1 addition & 6 deletions src/Zorg.Imaging/Drawing/Canvas.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ namespace Zorg.Imaging.Drawing;
/// beyond a million pixels are clamped.
/// </para>
/// <para>
/// The canvas is new and may still change, or move to its own package: using it needs the diagnostic
/// <c>ZORGDRAW</c> suppressed. It isn't safe to use from several threads at once.
/// It isn't safe to use from several threads at once.
/// </para>
/// </remarks>
/// <example>
Expand All @@ -36,12 +35,8 @@ namespace Zorg.Imaging.Drawing;
/// page.SaveAsPng(output);
/// </code>
/// </example>
[Experimental(Diagnostic)]
public sealed class Canvas : IDisposable
{
/// <summary>The diagnostic that marks the drawing API as new.</summary>
internal const string Diagnostic = "ZORGDRAW";

private readonly Rasterizer _rasterizer = new();
private Matrix3x2 _transform = Matrix3x2.Identity;
private float _tolerance = 0.2f;
Expand Down
3 changes: 0 additions & 3 deletions src/Zorg.Imaging/Drawing/FillRule.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using System.Diagnostics.CodeAnalysis;

namespace Zorg.Imaging.Drawing;

/// <summary>Which points a shape whose outline crosses itself, or has holes, covers.</summary>
/// <example><code>canvas.Fill(ring, black, FillRule.EvenOdd);</code></example>
[Experimental(Canvas.Diagnostic)]
public enum FillRule
{
/// <summary>
Expand Down
2 changes: 0 additions & 2 deletions src/Zorg.Imaging/Drawing/Shape.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;

namespace Zorg.Imaging.Drawing;

Expand All @@ -17,7 +16,6 @@ namespace Zorg.Imaging.Drawing;
/// canvas.Fill(triangle, new Rgba32(200, 0, 0));
/// </code>
/// </example>
[Experimental(Canvas.Diagnostic)]
public sealed class Shape
{
internal const byte Move = 0;
Expand Down
Loading
Loading