feat(codecs): add PNG decoder and ImageBuffer PNG encoding

Every colour type and bit depth (1/2/4/8/16), PLTE + tRNS (palette alpha
and colour keys), Adam7, all five filters, zlib via ZLibStream; CRC
mismatches and truncated data are tolerated with warnings. PngEncoder
gains an additive ImageBuffer overload (8/16-bit sRGB with sRGB chunk)
and the Palette colour type for decoding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:47:44 +00:00
1 parent 990c515b3b
commit 016a06d147
3 files changed
+671 -1

No files matched your search

+359
View File
@@ -0,0 +1,359 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
/// <summary>IHDR facts of a PNG stream.</summary>
public sealed record PngInfo(int Width, int Height, int BitDepth, PngColorType ColorType, bool Interlaced);
/// <summary>Decoded PNG pixels: interleaved, top-down, palette and tRNS expanded.</summary>
public sealed class PngImage
{
internal PngImage(PngInfo info, int channels, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList<string> warnings)
{
Info = info;
Channels = channels;
Pixels8 = pixels8;
Pixels16 = pixels16;
Warnings = warnings;
}
public PngInfo Info { get; }
public int Width => Info.Width;
public int Height => Info.Height;
/// <summary>1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA (palette → RGB/RGBA; tRNS adds alpha).</summary>
public int Channels { get; }
/// <summary>8 (<see cref="Pixels8"/>; 1/2/4-bit gray is scaled to 0..255) or 16 (<see cref="Pixels16"/>).</summary>
public int BitDepth => Pixels16 is null ? 8 : 16;
public byte[]? Pixels8 { get; }
public ushort[]? Pixels16 { get; }
/// <summary>Recoverable problems (CRC mismatches, truncated or corrupt image data, unknown critical chunks).</summary>
public IReadOnlyList<string> Warnings { get; }
}
/// <summary>
/// PNG decoder: every colour type and bit depth (1/2/4/8/16), PLTE + tRNS, Adam7, all five filters, zlib through
/// <see cref="ZLibStream"/>. CRC mismatches are tolerated with a warning; damaged image data yields the rows decoded so
/// far plus a warning. Ancillary colour chunks (gAMA, iCCP, cHRM) are ignored: samples are taken as sRGB.
/// </summary>
public static class PngDecoder
{
private static ReadOnlySpan<byte> Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
private static readonly (int X, int Y, int Dx, int Dy)[] Adam7 =
[(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)];
public static PngInfo ReadInfo(ReadOnlySpan<byte> data)
{
if (data.Length < 33 || !data.StartsWith(Signature) || !data.Slice(12, 4).SequenceEqual("IHDR"u8))
throw new InvalidDataException("PNG: missing signature or IHDR");
return ParseHeader(data.Slice(16, 13));
}
/// <param name="maxPixels">Upper bound on width × height, checked before allocation.</param>
public static PngImage Decode(ReadOnlySpan<byte> data, long maxPixels = 1L << 28)
{
var info = ReadInfo(data);
if ((long)info.Width * info.Height > maxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit");
var warnings = new List<string>();
byte[]? palette = null;
byte[]? trns = null;
using var idat = new MemoryStream();
var pos = 8;
var ended = false;
while (pos + 8 <= data.Length)
{
var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
var type = data.Slice(pos + 4, 4);
if (length > int.MaxValue || pos + 12 + (long)length > data.Length)
{
warnings.Add("PNG: truncated chunk");
break;
}
var body = data.Slice(pos + 8, (int)length);
var crc = BinaryPrimitives.ReadUInt32BigEndian(data[(pos + 8 + (int)length)..]);
if (Crc32.Compute(data.Slice(pos + 4, 4 + (int)length)) != crc) warnings.Add($"PNG: CRC mismatch in {Name(type)}");
pos += 12 + (int)length;
if (type.SequenceEqual("IDAT"u8))
{
idat.Write(body);
}
else if (type.SequenceEqual("PLTE"u8))
{
if (body.Length % 3 != 0 || body.Length > 768 || body.Length == 0) throw new InvalidDataException("PNG: bad PLTE");
palette = body.ToArray();
}
else if (type.SequenceEqual("tRNS"u8))
{
trns = body.ToArray();
}
else if (type.SequenceEqual("IEND"u8))
{
ended = true;
break;
}
else if (!type.SequenceEqual("IHDR"u8) && (type[0] & 0x20) == 0)
{
warnings.Add($"PNG: unknown critical chunk {Name(type)} ignored");
}
}
if (!ended) warnings.Add("PNG: missing IEND");
if (idat.Length == 0) throw new InvalidDataException("PNG: no image data");
if (info.ColorType == PngColorType.Palette && palette is null) throw new InvalidDataException("PNG: palette image without PLTE");
var layout = Layout.For(info, palette, trns);
idat.Position = 0;
using var z = new ZLibStream(idat, CompressionMode.Decompress);
return layout.Sixteen ? Decode16(info, layout, z, warnings) : Decode8(info, layout, z, warnings);
}
/// <summary>Decodes into a linear-light buffer (samples are sRGB-encoded; alpha stays linear).</summary>
/// <param name="expandGray">Return gray as three identical channels.</param>
/// <param name="keepAlpha">Keep alpha as a fourth channel (gray is then expanded).</param>
public static ImageBuffer DecodeToLinear(ReadOnlySpan<byte> data, bool expandGray = false, bool keepAlpha = false)
{
var image = Decode(data);
var gray = image.Channels <= 2;
var hasAlpha = image.Channels is 2 or 4;
var output = keepAlpha && hasAlpha ? 4 : gray && !expandGray ? 1 : 3;
return image.Pixels8 is { } p8
? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Channels, outputChannels: output)
: PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Channels, outputChannels: output);
}
private static string Name(ReadOnlySpan<byte> type) => string.Create(4, type.ToArray(), (s, t) =>
{
for (var i = 0; i < 4; i++) s[i] = t[i] is >= 32 and < 127 ? (char)t[i] : '?';
});
private static PngInfo ParseHeader(ReadOnlySpan<byte> h)
{
var width = BinaryPrimitives.ReadUInt32BigEndian(h);
var height = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
int depth = h[8], type = h[9];
if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) throw new InvalidDataException("PNG: bad dimensions");
var valid = type switch
{
0 => depth is 1 or 2 or 4 or 8 or 16,
3 => depth is 1 or 2 or 4 or 8,
2 or 4 or 6 => depth is 8 or 16,
_ => false,
};
if (!valid) throw new InvalidDataException($"PNG: invalid colour type {type} / bit depth {depth}");
if (h[10] != 0 || h[11] != 0 || h[12] > 1) throw new InvalidDataException("PNG: unsupported compression, filter or interlace method");
return new PngInfo((int)width, (int)height, depth, (PngColorType)type, h[12] == 1);
}
/// <summary>Sample geometry of the stored scanlines and of the expanded output.</summary>
private sealed class Layout
{
public int SourceChannels, BitsPerPixel, BytesPerPixel, OutChannels;
public bool Sixteen;
public byte[]? Palette;
public byte[]? PaletteAlpha;
/// <summary>tRNS colour key in source sample units (gray: 1 value, RGB: 3), or null.</summary>
public int[]? Key;
public static Layout For(PngInfo info, byte[]? palette, byte[]? trns)
{
var l = new Layout
{
SourceChannels = info.ColorType switch
{
PngColorType.Gray or PngColorType.Palette => 1,
PngColorType.GrayAlpha => 2,
PngColorType.Rgb => 3,
_ => 4,
},
Sixteen = info.BitDepth == 16,
};
l.BitsPerPixel = l.SourceChannels * info.BitDepth;
l.BytesPerPixel = Math.Max(1, l.BitsPerPixel / 8);
l.OutChannels = l.SourceChannels;
switch (info.ColorType)
{
case PngColorType.Palette:
l.Palette = palette;
l.OutChannels = 3;
if (trns is { Length: > 0 })
{
l.PaletteAlpha = new byte[256];
Array.Fill(l.PaletteAlpha, (byte)255);
trns.AsSpan(0, Math.Min(trns.Length, 256)).CopyTo(l.PaletteAlpha);
l.OutChannels = 4;
}
break;
case PngColorType.Gray when trns is { Length: >= 2 }:
l.Key = [trns[0] << 8 | trns[1]];
l.OutChannels = 2;
break;
case PngColorType.Rgb when trns is { Length: >= 6 }:
l.Key = [trns[0] << 8 | trns[1], trns[2] << 8 | trns[3], trns[4] << 8 | trns[5]];
l.OutChannels = 4;
break;
}
return l;
}
}
private static PngImage Decode8(PngInfo info, Layout l, Stream z, List<string> warnings)
{
var pixels = new byte[checked((long)info.Width * info.Height * l.OutChannels)];
var row = new byte[info.Width * l.OutChannels];
Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
{
Expand8(raw, info.BitDepth, count, l, row);
for (int i = 0, x = x0; i < count; i++, x += dx)
{
row.AsSpan(i * l.OutChannels, l.OutChannels).CopyTo(pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels)));
}
});
return new PngImage(info, l.OutChannels, pixels, null, warnings);
}
private static PngImage Decode16(PngInfo info, Layout l, Stream z, List<string> warnings)
{
var pixels = new ushort[checked((long)info.Width * info.Height * l.OutChannels)];
Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
{
for (int i = 0, x = x0; i < count; i++, x += dx)
{
var dst = pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels), l.OutChannels);
var transparent = l.Key is not null;
for (var c = 0; c < l.SourceChannels; c++)
{
dst[c] = BinaryPrimitives.ReadUInt16BigEndian(raw[((i * l.SourceChannels + c) * 2)..]);
if (l.Key is not null && dst[c] != l.Key[c]) transparent = false;
}
if (l.Key is not null) dst[l.SourceChannels] = transparent ? (ushort)0 : ushort.MaxValue;
}
});
return new PngImage(info, l.OutChannels, null, pixels, warnings);
}
private delegate void RowHandler(ReadOnlySpan<byte> raw, int y, int x0, int dx, int count);
/// <summary>Streams every (pass,) row out of zlib, unfilters it and hands the raw samples to <paramref name="handle"/>.</summary>
private static void Inflate(PngInfo info, Layout l, Stream z, List<string> warnings, RowHandler handle)
{
var passes = info.Interlaced ? Adam7 : [(0, 0, 1, 1)];
var maxRow = (int)(((long)info.Width * l.BitsPerPixel + 7) / 8);
var line = new byte[maxRow + 1];
var prior = new byte[maxRow];
try
{
foreach (var (px, py, dx, dy) in passes)
{
if (px >= info.Width || py >= info.Height) continue;
var count = (info.Width - px + dx - 1) / dx;
var rowBytes = (int)(((long)count * l.BitsPerPixel + 7) / 8);
Array.Clear(prior);
for (var y = py; y < info.Height; y += dy)
{
var buffer = line.AsSpan(0, rowBytes + 1);
if (z.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) < buffer.Length)
{
warnings.Add("PNG: image data truncated");
return;
}
if (buffer[0] > 4)
{
warnings.Add($"PNG: invalid filter type {buffer[0]}");
return;
}
var row = buffer[1..];
Unfilter(buffer[0], row, prior.AsSpan(0, rowBytes), l.BytesPerPixel);
handle(row, y, px, dx, count);
row.CopyTo(prior);
}
}
}
catch (InvalidDataException ex)
{
warnings.Add("PNG: corrupt image data: " + ex.Message);
}
}
private static void Unfilter(int filter, Span<byte> row, ReadOnlySpan<byte> prior, int bpp)
{
switch (filter)
{
case 1:
for (var i = bpp; i < row.Length; i++) row[i] += row[i - bpp];
break;
case 2:
for (var i = 0; i < row.Length; i++) row[i] += prior[i];
break;
case 3:
for (var i = 0; i < bpp && i < row.Length; i++) row[i] += (byte)(prior[i] >> 1);
for (var i = bpp; i < row.Length; i++) row[i] += (byte)((row[i - bpp] + prior[i]) >> 1);
break;
case 4:
for (var i = 0; i < bpp && i < row.Length; i++) row[i] += prior[i];
for (var i = bpp; i < row.Length; i++) row[i] += (byte)PngEncoder.Paeth(row[i - bpp], prior[i], prior[i - bpp]);
break;
}
}
/// <summary>Expands one row of ≤ 8-bit samples (sub-byte gray, palette, tRNS key) to 8-bit output channels.</summary>
private static void Expand8(ReadOnlySpan<byte> raw, int depth, int count, Layout l, Span<byte> dst)
{
var oc = l.OutChannels;
if (depth == 8 && l.Palette is null && l.Key is null)
{
raw[..(count * oc)].CopyTo(dst);
return;
}
if (depth == 8 && l.Key is not null)
{
var sc = l.SourceChannels;
for (var i = 0; i < count; i++)
{
var opaque = false;
for (var c = 0; c < sc; c++)
{
var v = raw[i * sc + c];
dst[i * oc + c] = v;
if (v != l.Key[c]) opaque = true;
}
dst[i * oc + sc] = opaque ? (byte)255 : (byte)0;
}
return;
}
// Sub-byte or palette: one sample per pixel, MSB first.
var mask = (1 << depth) - 1;
var scale = l.Palette is null ? 255 / mask : 1;
for (var i = 0; i < count; i++)
{
var bit = i * depth;
var v = (raw[bit >> 3] >> (8 - depth - (bit & 7))) & mask;
if (l.Palette is { } pal)
{
var o = dst.Slice(i * oc, oc);
if (3 * v + 2 < pal.Length)
{
o[0] = pal[3 * v];
o[1] = pal[3 * v + 1];
o[2] = pal[3 * v + 2];
}
else
{
o[..3].Clear(); // out-of-range index: black, as libpng
}
if (oc == 4) o[3] = l.PaletteAlpha![v];
}
else
{
dst[i * oc] = (byte)(v * scale);
if (l.Key is not null) dst[i * oc + 1] = v == l.Key[0] ? (byte)0 : (byte)255;
}
}
}
}
+34 -1
View File
@@ -1,14 +1,16 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
/// <summary>PNG colour types written by <see cref="PngEncoder"/>.</summary>
/// <summary>PNG colour types (<see cref="Palette"/> is decoded but never written by <see cref="PngEncoder"/>).</summary>
public enum PngColorType : byte
{
Gray = 0,
Rgb = 2,
Palette = 3,
GrayAlpha = 4,
Rgba = 6,
}
@@ -29,6 +31,7 @@ public static class PngEncoder
public static void Encode(Stream output, ReadOnlySpan<byte> pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
if (colorType == PngColorType.Palette) throw new ArgumentException("Palette images are not written", nameof(colorType));
var channels = colorType switch
{
PngColorType.Gray => 1,
@@ -60,6 +63,36 @@ public static class PngEncoder
WriteChunk(output, "IEND", []);
}
/// <summary>Encodes a linear-light buffer as sRGB-encoded PNG (1 channel → gray, 3 → RGB, 4 → RGBA with linear
/// alpha) and tags it with an sRGB chunk.</summary>
/// <param name="bitDepth">8 or 16 bits per sample.</param>
public static byte[] Encode(ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize)
{
using var ms = new MemoryStream();
Encode(ms, image, bitDepth, level);
return ms.ToArray();
}
public static void Encode(Stream output, ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
var channels = image.Channels;
var colorType = channels switch { 1 => PngColorType.Gray, 3 => PngColorType.Rgb, _ => PngColorType.Rgba };
byte[] pixels;
if (bitDepth == 8)
{
pixels = PixelConvert.ToInterleaved8(image, channels);
}
else
{
var words = PixelConvert.ToInterleaved16(image, channels);
pixels = new byte[words.Length * 2];
for (var i = 0; i < words.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(pixels.AsSpan(2 * i), words[i]);
}
IEnumerable<(string Type, byte[] Data)> chunks = [("sRGB", [0]), .. extraChunks ?? []];
Encode(output, pixels, image.Width, image.Height, colorType, bitDepth, level, chunks);
}
/// <summary>Filters every row (adaptive, minimum sum of absolute differences) and deflates the result.</summary>
public static byte[] Compress(ReadOnlySpan<byte> pixels, int height, int stride, int bpp, CompressionLevel level)
{