Files
Febe/tests/Febe.Tests/Imaging/TestImages.cs
T
Alby96andClaude Opus 5.5 8bf76f18ff Lettori PNG, GIF e BMP e scrittore PNG di casa (C1, passo 2)
Prima parte dei codec d'immagine scritti in casa per togliere SkiaSharp (decisione di Alberto del 18 novembre 2026: niente componenti esterni). In Febe.Core/Codecs/Images: la base comune (RgbaImage RGBA a 8 bit non premoltiplicata, anche dal pool; ImageLimits controllati prima di ogni allocazione; ImageDecodeException e sottotipi per limiti e formati non letti; riconoscimento del formato dai primi byte; facciata ImageDecoder), il lettore PNG (tutti i tipi di colore e le profondità, tavolozza e tRNS, Adam7, i cinque filtri, CRC di ogni blocco, metadati eXIf, iCCP, tEXt, zTXt, iTXt e XMP, numero dei fotogrammi APNG), lo scrittore PNG (RGB/RGBA a 8 bit, filtro adattivo per riga, eXIf, iCCP, XMP), il lettore GIF (LZW, primo fotogramma, trasparenza, interlacciamento, tavolozze, numero dei fotogrammi) e il lettore BMP (1-32 bit, BI_RGB, BITFIELDS, RLE8, RLE4, PNG dentro, dal basso e dall'alto). CRC-32 e LZW sono nostri, zlib è quello della BCL.

Le prove leggono i 37 riferimenti PNG, GIF e BMP e li trovano uguali byte per byte alle immagini attese, lette a loro volta con il nostro lettore PNG verificato contro un lettore minimo indipendente; poi andate e ritorno dello scrittore, metadati, file danneggiati e tagliati, limiti, e modifiche casuali a seme fisso che devono dare un'immagine o un'ImageDecodeException e nient'altro. Una riga in decisioni.md dice le scelte di lettura.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:26:58 +01:00

302 lines
11 KiB
C#

using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Small images and files built by the tests: random RGBA images from a fixed seed, and PNG, GIF and BMP files written
/// byte by byte from the specifications, to reach the cases the reference set does not have (damaged files above all).
/// </summary>
internal static class TestImages
{
/// <summary>An image of random pixels; <paramref name="opaque"/> forces alpha 255.</summary>
public static RgbaImage Random(int width, int height, int seed, bool opaque = false)
{
var random = new Random(seed);
var pixels = new byte[width * height * 4];
random.NextBytes(pixels);
if (opaque)
{
for (var i = 3; i < pixels.Length; i += 4)
{
pixels[i] = 255;
}
}
return new RgbaImage(width, height, pixels);
}
/// <summary>A smooth image (gradients and a little noise), the kind adaptive filtering is for.</summary>
public static RgbaImage Gradient(int width, int height, int seed)
{
var random = new Random(seed);
var image = new RgbaImage(width, height);
for (var y = 0; y < height; y++)
{
var row = image.GetRow(y);
for (var x = 0; x < width; x++)
{
row[x * 4] = (byte)(x * 255 / Math.Max(1, width - 1));
row[(x * 4) + 1] = (byte)(y * 255 / Math.Max(1, height - 1));
row[(x * 4) + 2] = (byte)((x + y + random.Next(3)) & 0xFF);
row[(x * 4) + 3] = (byte)(255 - (x & 0x3F));
}
}
return image;
}
/// <summary>The chunks of a PNG: type and payload, in order (the CRC is checked).</summary>
public static List<(string Type, byte[] Payload)> PngChunks(byte[] png)
{
var chunks = new List<(string, byte[])>();
var pos = 8;
while (pos < png.Length)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
var type = Encoding.ASCII.GetString(png, pos + 4, 4);
Assert.AreEqual(Crc32.Compute(png.AsSpan(pos + 4, length + 4)), BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), $"CRC di {type}");
chunks.Add((type, png.AsSpan(pos + 8, length).ToArray()));
pos += length + 12;
}
return chunks;
}
/// <summary>Writes a PNG from its chunks (signature and CRCs added).</summary>
public static byte[] Png(params (string Type, byte[] Payload)[] chunks)
{
using var output = new MemoryStream();
output.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
foreach (var (type, payload) in chunks)
{
output.Write(Chunk(type, payload));
}
return output.ToArray();
}
/// <summary>One chunk: length, type, payload, CRC.</summary>
public static byte[] Chunk(string type, byte[] payload)
{
var chunk = new byte[payload.Length + 12];
BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)payload.Length);
Encoding.ASCII.GetBytes(type, chunk.AsSpan(4));
payload.CopyTo(chunk, 8);
BinaryPrimitives.WriteUInt32BigEndian(chunk.AsSpan(8 + payload.Length), Crc32.Compute(chunk.AsSpan(4, payload.Length + 4)));
return chunk;
}
/// <summary>An IHDR payload.</summary>
public static byte[] Ihdr(int width, int height, int depth, int colorType, int interlace = 0)
{
var payload = new byte[13];
BinaryPrimitives.WriteUInt32BigEndian(payload, (uint)width);
BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(4), (uint)height);
payload[8] = (byte)depth;
payload[9] = (byte)colorType;
payload[12] = (byte)interlace;
return payload;
}
/// <summary>The zlib stream of <paramref name="data"/>.</summary>
public static byte[] Zlib(byte[] data)
{
using var output = new MemoryStream();
using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(data);
}
return output.ToArray();
}
/// <summary>Latin-1 bytes of a keyword or text.</summary>
public static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text);
/// <summary>Concatenation of byte arrays.</summary>
public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
/// <summary>Recomputes the CRC of every chunk of a PNG whose bytes were changed (stops at the first broken length).</summary>
public static void FixPngCrcs(byte[] png)
{
var pos = 8;
while (pos + 12 <= png.Length)
{
var length = BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
if (length > png.Length - pos - 12)
{
return;
}
BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(pos + 8 + (int)length), Crc32.Compute(png.AsSpan(pos + 4, (int)length + 4)));
pos += (int)length + 12;
}
}
/// <summary>
/// GIF LZW data sub-blocks for <paramref name="indices"/> that use only literal codes: a clear code every few
/// literals keeps the code size at <paramref name="minCodeSize"/> + 1. Ends with the end code and the terminator.
/// </summary>
public static byte[] GifLiteralLzw(ReadOnlySpan<byte> indices, int minCodeSize)
{
var clear = 1 << minCodeSize;
var codeSize = minCodeSize + 1;
var perGroup = Math.Max(1, clear - 2);
var bits = new List<byte>();
ulong accumulator = 0;
var count = 0;
void Emit(int code)
{
accumulator |= (ulong)code << count;
count += codeSize;
while (count >= 8)
{
bits.Add((byte)accumulator);
accumulator >>= 8;
count -= 8;
}
}
for (var i = 0; i < indices.Length; i++)
{
if (i % perGroup == 0)
{
Emit(clear);
}
Emit(indices[i]);
}
Emit(clear + 1);
if (count > 0)
{
bits.Add((byte)accumulator);
}
var output = new List<byte>();
for (var i = 0; i < bits.Count; i += 255)
{
var n = Math.Min(255, bits.Count - i);
output.Add((byte)n);
output.AddRange(bits.GetRange(i, n));
}
output.Add(0);
return output.ToArray();
}
/// <summary>A GIF89a file: header, logical screen, optional global palette, then the given blocks and the trailer.</summary>
public static byte[] Gif(int width, int height, byte[]? globalPalette, params byte[][] blocks)
{
var output = new List<byte>();
output.AddRange("GIF89a"u8.ToArray());
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
output.Add(globalPalette is null ? (byte)0 : (byte)(0x80 | PaletteSizeBits(globalPalette)));
output.Add(0);
output.Add(0);
if (globalPalette is not null)
{
output.AddRange(globalPalette);
}
foreach (var block in blocks)
{
output.AddRange(block);
}
output.Add(0x3B);
return output.ToArray();
}
/// <summary>A graphic control extension with a transparent index (or none with -1).</summary>
public static byte[] GifControl(int transparent) =>
[0x21, 0xF9, 4, transparent >= 0 ? (byte)1 : (byte)0, 0, 0, transparent >= 0 ? (byte)transparent : (byte)0, 0];
/// <summary>An image block: descriptor, optional local palette, LZW data of <paramref name="indices"/>.</summary>
public static byte[] GifFrame(int left, int top, int width, int height, ReadOnlySpan<byte> indices, int minCodeSize, byte[]? localPalette = null, bool interlaced = false)
{
var output = new List<byte> { 0x2C };
output.AddRange(BitConverter.GetBytes((ushort)left));
output.AddRange(BitConverter.GetBytes((ushort)top));
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
var packed = interlaced ? 0x40 : 0;
if (localPalette is not null)
{
packed |= 0x80 | PaletteSizeBits(localPalette);
}
output.Add((byte)packed);
if (localPalette is not null)
{
output.AddRange(localPalette);
}
output.Add((byte)minCodeSize);
output.AddRange(GifLiteralLzw(indices, minCodeSize));
return output.ToArray();
}
private static int PaletteSizeBits(byte[] palette)
{
var entries = palette.Length / 3;
var bits = 0;
while ((2 << bits) < entries)
{
bits++;
}
Assert.AreEqual(2 << bits, entries, "la tavolozza di un GIF ha 2, 4, 8... voci");
return bits;
}
/// <summary>
/// A BMP with an information header of <paramref name="headerSize"/> bytes (40, 108, 124...; 12 for a core header),
/// then <paramref name="afterHeader"/> (masks, palette) and the pixel data.
/// </summary>
public static byte[] Bmp(int headerSize, int width, int height, int bitsPerPixel, uint compression, byte[] afterHeader, byte[] pixels, uint colorsUsed = 0, uint[]? masks = null)
{
var info = new byte[headerSize];
BinaryPrimitives.WriteUInt32LittleEndian(info, (uint)headerSize);
if (headerSize == 12)
{
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(4), (ushort)width);
BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(6), (short)height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(8), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(10), (ushort)bitsPerPixel);
}
else
{
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(4), width);
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(8), height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(12), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(14), (ushort)bitsPerPixel);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(16), compression);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(20), (uint)pixels.Length);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(32), colorsUsed);
if (masks is not null)
{
for (var i = 0; i < masks.Length; i++)
{
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(40 + (i * 4)), masks[i]);
}
}
}
var offset = 14 + headerSize + afterHeader.Length;
var file = new byte[offset + pixels.Length];
file[0] = (byte)'B';
file[1] = (byte)'M';
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(2), (uint)file.Length);
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(10), (uint)offset);
info.CopyTo(file, 14);
afterHeader.CopyTo(file, 14 + headerSize);
pixels.CopyTo(file, offset);
return file;
}
}