using System.Buffers.Binary; using System.IO.Compression; using System.Text; using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// 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). /// internal static class TestImages { /// An image of random pixels; forces alpha 255. 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); } /// A smooth image (gradients and a little noise), the kind adaptive filtering is for. 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; } /// The chunks of a PNG: type and payload, in order (the CRC is checked). 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; } /// Writes a PNG from its chunks (signature and CRCs added). 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(); } /// One chunk: length, type, payload, CRC. 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; } /// An IHDR payload. 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; } /// The zlib stream of . 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(); } /// Latin-1 bytes of a keyword or text. public static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text); /// Concatenation of byte arrays. public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray(); /// Recomputes the CRC of every chunk of a PNG whose bytes were changed (stops at the first broken length). 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; } } /// /// GIF LZW data sub-blocks for that use only literal codes: a clear code every few /// literals keeps the code size at + 1. Ends with the end code and the terminator. /// public static byte[] GifLiteralLzw(ReadOnlySpan indices, int minCodeSize) { var clear = 1 << minCodeSize; var codeSize = minCodeSize + 1; var perGroup = Math.Max(1, clear - 2); var bits = new List(); 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(); 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(); } /// A GIF89a file: header, logical screen, optional global palette, then the given blocks and the trailer. public static byte[] Gif(int width, int height, byte[]? globalPalette, params byte[][] blocks) { var output = new List(); 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(); } /// A graphic control extension with a transparent index (or none with -1). public static byte[] GifControl(int transparent) => [0x21, 0xF9, 4, transparent >= 0 ? (byte)1 : (byte)0, 0, 0, transparent >= 0 ? (byte)transparent : (byte)0, 0]; /// An image block: descriptor, optional local palette, LZW data of . public static byte[] GifFrame(int left, int top, int width, int height, ReadOnlySpan indices, int minCodeSize, byte[]? localPalette = null, bool interlaced = false) { var output = new List { 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; } /// /// A BMP with an information header of bytes (40, 108, 124...; 12 for a core header), /// then (masks, palette) and the pixel data. /// 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; } }