Files
Febe/tests/Febe.Tests/Imaging/ImageProcessingTests.cs
Alby96andClaude Opus 5.5 7e8296e790 Correzioni della revisione dei codec di casa (C1)
Correggo i difetti confermati dalla revisione di funzione/codec-immagini e
aggiungo le prove che li avrebbero trovati.

- JPEG: una tabella di Huffman con troppi codici corti dava
  ArgumentOutOfRangeException invece di ImageDecodeException, e un file
  rovinato faceva fallire importazione e ricostruzione; ora il controllo si
  fa prima di scrivere le voci. La prova che diceva di coprirlo cadeva invece
  su «tabella troncata»: ora tiene il totale giusto e controlla il messaggio.
- JPEG: il troncamento delle scansioni di Huffman si vede a ogni riga di MCU,
  non dopo l'ultimo MCU (un file tagliato dopo le intestazioni costava 6,7 s).
- JPEG: IDCT ridotta a 1/2 e 1/4 calcolata dai coefficienti; miniatura di una
  foto 4000x3000 da 126 a 59 ms in Release. Il predittore senza perdita non
  cerca più l'indice della componente a ogni campione.
- WebP: con livello del filtro del fotogramma 0 il filtro è spento, come nei
  decodificatori di riferimento; VP8L costruisce solo i gruppi nominati dai
  meta codici (prima fino a 335 MB di tabelle da 160 KB di file).
- BMP OS/2: altezza senza segno e sempre dal basso.
- Array di lavoro dei codec oltre 16 MiB fuori dal pool condiviso, che li
  avrebbe tenuti dopo l'uso.
- Conversione: profilo ICC copiato solo se RGB, profondità oltre 8 bit e
  blocchi gAMA/cHRM/sRGB dichiarati in NotCarried, Lossy vero quando si perde
  precisione.
- Impronta e misure di una foto da una sola lettura e decodifica; ReadSize
  legge solo l'inizio di JPEG, GIF e BMP.
- docs: decisioni (righe aggiunte, con la correzione dei 2,0 MB del set di
  riferimento) e windows.md (Febe.exe rimisurato: 85,6 MB, a capo sistemato).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:52:17 +01:00

689 lines
29 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
using Febe.Core.Codecs.Images;
using Febe.Core.Drawing;
using Scenes = Febe.Tests.Support.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>
/// What replaced SkiaSharp around the codecs: the resampler, EXIF orientation, the JPEG decoded smaller, the converter
/// that keeps metadata, PNG texts and the anti-aliased rasteriser of <see cref="Canvas"/>.
/// </summary>
[TestClass]
public sealed class ImageProcessingTests
{
// ---- Resampler ----
[TestMethod]
[DataRow(4000, 3000, 480, 480, 360)]
[DataRow(3024, 4032, 480, 360, 480)]
[DataRow(100, 50, 480, 100, 50)]
[DataRow(5000, 2, 480, 480, 1)]
[DataRow(1081, 1081, 480, 480, 480)]
public void FitWithinKeepsTheProportionsAndNeverEnlarges(int width, int height, int longSide, int expectedWidth, int expectedHeight) =>
Assert.AreEqual((expectedWidth, expectedHeight), ImageResampler.FitWithin(width, height, longSide));
[TestMethod]
[DataRow(ResampleFilter.Lanczos3, false)]
[DataRow(ResampleFilter.Lanczos3, true)]
[DataRow(ResampleFilter.Area, false)]
[DataRow(ResampleFilter.Area, true)]
public void AFlatColourStaysFlat(ResampleFilter filter, bool linearLight)
{
using var source = Flat(301, 199, 40, 120, 210, 255);
foreach (var (w, h) in new[] { (100, 66), (37, 211), (602, 398), (1, 1) })
{
using var result = ImageResampler.Resize(source, w, h, new ResampleOptions { Filter = filter, LinearLight = linearLight });
Assert.AreEqual((w, h), (result.Width, result.Height));
AssertEveryPixel(result, (40, 120, 210, 255), 1, $"{filter} {w}×{h}");
}
}
[TestMethod]
public void TheSameSizeGivesTheSamePixels()
{
using var source = TestImages.Gradient(64, 48, 3);
using var result = ImageResampler.Resize(source, 64, 48);
ImageAssert.AreEqual(source, result, "stessa misura");
}
[TestMethod]
public void TheAreaFilterAveragesWholeBlocks()
{
using var source = TestImages.Random(40, 30, 5, opaque: true);
using var result = ImageResampler.Resize(source, 20, 15, new ResampleOptions { Filter = ResampleFilter.Area });
for (var y = 0; y < 15; y++)
{
for (var x = 0; x < 20; x++)
{
var actual = result.GetPixel(x, y);
for (var channel = 0; channel < 3; channel++)
{
var sum = 0;
for (var dy = 0; dy < 2; dy++)
{
for (var dx = 0; dx < 2; dx++)
{
sum += source.GetRow((2 * y) + dy)[(((2 * x) + dx) * 4) + channel];
}
}
var value = channel switch { 0 => actual.R, 1 => actual.G, _ => actual.B };
Assert.IsLessThanOrEqualTo(1.0, Math.Abs(value - (sum / 4.0)), $"({x}, {y}) canale {channel}");
}
}
}
}
[TestMethod]
public void TransparentPixelsLendNoColour()
{
// Left half transparent black-ish noise, right half opaque orange: averaging premultiplied, the edge stays orange.
var pixels = new byte[64 * 16 * 4];
new Random(7).NextBytes(pixels);
for (var y = 0; y < 16; y++)
{
for (var x = 0; x < 64; x++)
{
var i = ((y * 64) + x) * 4;
if (x < 32)
{
pixels[i + 3] = 0;
}
else
{
(pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]) = (250, 140, 20, 255);
}
}
}
using var source = new RgbaImage(64, 16, pixels);
using var result = ImageResampler.Resize(source, 16, 4);
for (var y = 0; y < 4; y++)
{
for (var x = 0; x < 16; x++)
{
var p = result.GetPixel(x, y);
if (p.A >= 8)
{
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.R - 250), $"({x}, {y}) {p}");
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.G - 140), $"({x}, {y}) {p}");
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.B - 20), $"({x}, {y}) {p}");
}
}
}
}
[TestMethod]
public void LinearLightAveragesTheLightNotTheCodes()
{
// Black and white stripes one pixel wide: half the light is sRGB 188, half the code is 128.
using var stripes = new RgbaImage(64, 8);
for (var y = 0; y < 8; y++)
{
var row = stripes.GetRow(y);
for (var x = 0; x < 64; x++)
{
var v = (byte)((x & 1) == 0 ? 0 : 255);
(row[x * 4], row[(x * 4) + 1], row[(x * 4) + 2], row[(x * 4) + 3]) = (v, v, v, 255);
}
}
using var codes = ImageResampler.Resize(stripes, 16, 2, new ResampleOptions { Filter = ResampleFilter.Area });
using var light = ImageResampler.Resize(stripes, 16, 2, new ResampleOptions { Filter = ResampleFilter.Area, LinearLight = true });
Assert.IsLessThanOrEqualTo(1, Math.Abs(codes.GetPixel(8, 1).R - 128));
Assert.IsLessThanOrEqualTo(1, Math.Abs(light.GetPixel(8, 1).R - 188));
}
[TestMethod]
public void LanczosReducesFaithfully()
{
using var scene = Scenes.Scene(4, 1600, 1200);
using var lanczos = ImageResampler.Resize(scene, 400, 300);
using var area = ImageResampler.Resize(scene, 400, 300, new ResampleOptions { Filter = ResampleFilter.Area });
var quality = ImageQuality.Compare(area, lanczos);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
// ---- Orientation ----
[TestMethod]
public void EveryOrientationIsShownAsTheSpecificationSays()
{
using var stored = TestImages.Random(7, 4, 11);
for (var orientation = 1; orientation <= 8; orientation++)
{
using var expected = ImageQuality.Orient(stored, orientation);
var shown = ImageOrientation.Apply(stored, orientation);
try
{
ImageAssert.AreEqual(expected, shown, $"orientamento {orientation}");
Assert.AreEqual((expected.Width, expected.Height), ImageOrientation.ShownSize(7, 4, orientation));
}
finally
{
if (!ReferenceEquals(shown, stored))
{
shown.Dispose();
}
}
}
}
[TestMethod]
public void UprightIsTheSameImageAndInvalidValuesCountAsUpright()
{
using var stored = TestImages.Random(5, 3, 2);
Assert.AreSame(stored, ImageOrientation.Apply(stored, 1));
Assert.AreEqual((5, 3), ImageOrientation.ShownSize(5, 3, 0));
Assert.AreEqual((5, 3), ImageOrientation.ShownSize(5, 3, 9));
}
// ---- JPEG decoded smaller ----
[TestMethod]
[DataRow(1)]
[DataRow(2)]
[DataRow(3)]
public void AJpegDecodedSmallerLooksLikeTheFullDecodeReduced(int reduction)
{
using var scene = Scenes.Scene(5, 803, 601);
foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 })
{
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 92, Subsampling = subsampling });
using var small = JpegDecoder.DecodeReduced(jpeg, reduction, out var info);
var scale = 1 << reduction;
Assert.AreEqual(((803 + scale - 1) / scale, (601 + scale - 1) / scale), (small.Width, small.Height), $"1/{scale}");
Assert.AreEqual((803, 601), (info.Width, info.Height), "le misure dichiarate restano quelle del file");
using var full = JpegDecoder.Decode(jpeg);
using var expected = ImageResampler.Resize(full, small.Width, small.Height, new ResampleOptions { Filter = ResampleFilter.Area });
var quality = ImageQuality.Compare(expected, small);
Assert.IsGreaterThan(reduction == 3 ? 24.0 : 27.0, quality.MinPsnr, $"1/{scale} {subsampling}: {quality}");
}
}
[TestMethod]
public void TheReducedTransformIsTheMeanOfTheFullOne()
{
// InverseReduced computes the means of 2×2 and 4×4 squares of the full inverse straight from the
// coefficients; checked against the T.81 definition in double precision, averaged, then rounded and clamped.
var random = new Random(91);
var quantization = new ushort[64];
var block = new short[64];
Span<byte> output = stackalloc byte[16];
for (var round = 0; round < 400; round++)
{
for (var i = 0; i < 64; i++)
{
quantization[i] = (ushort)random.Next(1, 24);
// Mostly small coefficients, some zero rows and columns, now and then a large one.
var zero = random.Next(4) == 0 || (round % 5 == 0 && i >= 8);
block[i] = zero ? (short)0 : (short)random.Next(-40, 41);
}
block[0] = (short)random.Next(-60, 61);
var full = new double[64];
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
double sum = 0;
for (var v = 0; v < 8; v++)
{
for (var u = 0; u < 8; u++)
{
var cu = u == 0 ? 1 / Math.Sqrt(2) : 1;
var cv = v == 0 ? 1 / Math.Sqrt(2) : 1;
sum += cu * cv * block[(v * 8) + u] * quantization[(v * 8) + u]
* Math.Cos(((2 * x) + 1) * u * Math.PI / 16) * Math.Cos(((2 * y) + 1) * v * Math.PI / 16);
}
}
full[(y * 8) + x] = (sum / 4) + 128;
}
}
foreach (var shift in new[] { 1, 2 })
{
var n = 8 >> shift;
var side = 1 << shift;
JpegDct.InverseReduced(block, quantization, output, n, 8, [], shift);
for (var y = 0; y < n; y++)
{
for (var x = 0; x < n; x++)
{
double mean = 0;
for (var dy = 0; dy < side; dy++)
{
for (var dx = 0; dx < side; dx++)
{
mean += full[(((y * side) + dy) * 8) + (x * side) + dx];
}
}
var expected = Math.Clamp((int)Math.Floor((mean / (side * side)) + 0.5), 0, 255);
Assert.IsLessThanOrEqualTo(1, Math.Abs(expected - output[(y * n) + x]), $"giro {round}, 1/{side}, ({x}, {y})");
}
}
}
}
}
[TestMethod]
public void DecodeAtLeastShrinksOnlyWhileTheLongSideIsEnough()
{
using var scene = Scenes.Scene(6, 4000, 3000);
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 80 });
foreach (var (min, expected) in new[] { (4000, 4000), (2000, 2000), (1999, 2000), (960, 1000), (480, 500), (100, 500) })
{
using var image = ImageDecoder.DecodeAtLeast(jpeg, min, out _);
Assert.AreEqual(expected, image.Width, $"almeno {min}");
}
// Formats without a reduced decode come back whole.
var png = PngEncoder.Encode(TestImages.Random(300, 200, 1, opaque: true));
using var whole = ImageDecoder.DecodeAtLeast(png, 50, out _);
Assert.AreEqual(300, whole.Width);
}
// ---- Converter ----
[TestMethod]
public void AJpegBecomesPngAndWebPWithItsMetadataAndOrientationTag()
{
using var scene = Scenes.Scene(7, 320, 200);
var exif = Tiff(orientation: 6);
var icc = Profile(612);
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF/></x:xmpmeta>";
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 90, Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["Gita al lago"] });
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
{
var result = ImageConverter.Convert(jpeg, target);
Assert.AreEqual((ImageFormat.Jpeg, target), (result.Source, result.Target));
Assert.IsFalse(result.Lossy);
using var back = ImageDecoder.Decode(result.Data, out var info);
Assert.AreEqual(target, info.Format);
Assert.AreEqual((320, 200), (back.Width, back.Height), "i pixel non si ruotano: l'etichetta resta");
Assert.AreEqual(6, info.Metadata.Orientation);
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual(xmp, info.Metadata.Xmp);
using var original = JpegDecoder.Decode(jpeg);
ImageAssert.AreEqual(original, back, $"in {target} senza perdita");
if (target == ImageFormat.Png)
{
Assert.IsEmpty(result.NotCarried);
Assert.AreEqual("Gita al lago", info.Metadata.Texts.Single(t => t.Keyword == "Comment").Text);
}
else
{
Assert.HasCount(1, result.NotCarried);
StringAssert.Contains(result.NotCarried[0], "WebP");
}
}
}
[TestMethod]
public void APngBecomesJpegWithItsMetadataOverWhite()
{
using var image = TestImages.Gradient(96, 64, 9); // alpha falls from 255 to 192 across each band of 64 columns
var exif = Tiff(orientation: 3);
var icc = Profile(300);
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>";
var png = PngEncoder.Encode(image, new PngEncoderOptions
{
Exif = exif,
IccProfile = icc,
Xmp = xmp,
Texts = [new ImageText("Title", "Tramonto"), new ImageText("Description", "Città e mare")],
});
var result = ImageConverter.Convert(png, ImageFormat.Jpeg);
Assert.IsTrue(result.Lossy);
Assert.HasCount(1, result.NotCarried);
StringAssert.Contains(result.NotCarried[0], "trasparenza");
using var back = ImageDecoder.Decode(result.Data, out var info);
Assert.IsTrue(back.IsOpaque());
Assert.AreEqual(3, info.Metadata.Orientation);
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual(xmp, info.Metadata.Xmp);
CollectionAssert.AreEqual(new[] { "Title: Tramonto", "Description: Città e mare" }, info.Metadata.Texts.Select(t => t.Text).ToArray());
// Over white: a pixel at alpha 192 is lighter than its colour.
var (r, _, _, a) = image.GetPixel(63, 10);
Assert.AreEqual(192, a);
var expected = ((r * 192) + (255 * 63) + 127) / 255;
Assert.IsLessThanOrEqualTo(6, Math.Abs(back.GetPixel(63, 10).R - expected));
}
[TestMethod]
public void AProfileThatDoesNotDescribeRgbIsLeftBehind()
{
// Adobe CMYK, every pixel the same inks: the decoder writes RGB, so a CMYK profile no longer fits.
const int width = 16;
const int height = 8;
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray();
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1);
var cmykFile = WithIcc(JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK"));
Assert.AreEqual("CMYK", ImageConverter.IccColorSpace(JpegDecoder.Identify(cmykFile).Metadata.IccProfile));
// A grey JPEG with a grey profile: the encoders write RGB.
using var scene = Scenes.Scene(8, 48, 32);
var greyFile = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") });
foreach (var (file, space) in new[] { (cmykFile, "CMYK"), (greyFile, "grigi") })
{
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg })
{
var result = ImageConverter.Convert(file, target);
var said = string.Join("; ", result.NotCarried);
Assert.IsNull(result.Metadata.IccProfile, $"{space} in {target}");
Assert.IsNull(result.Metadata.IccProfileName, $"{space} in {target}");
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal) && n.Contains(space, StringComparison.Ordinal)), $"{space} in {target}: {said}");
Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.IccProfile, $"{space} in {target}: il file scritto non ha il profilo");
}
}
// An RGB profile travels (the other converter tests check it byte for byte); one too short to have a
// colour space does not.
Assert.AreEqual("RGB ", ImageConverter.IccColorSpace(Profile(200)));
Assert.IsNull(ImageConverter.IccColorSpace(new byte[12]));
var garbled = JpegEncoder.Encode(scene, new JpegEncoderOptions { IccProfile = new byte[12] });
var dropped = ImageConverter.Convert(garbled, ImageFormat.Png);
Assert.IsNull(dropped.Metadata.IccProfile);
Assert.IsTrue(dropped.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal)));
}
[TestMethod]
public void SixteenBitSamplesAndPngColourChunksAreReported()
{
// A 2×2 16-bit RGB PNG with gAMA and sRGB: decoded to 8 bits, so not lossless, and the colour chunks stay
// behind; both are said.
var raw = new byte[2 * (1 + (2 * 6))];
for (var i = 0; i < raw.Length; i++)
{
raw[i] = i % 13 == 0 ? (byte)0 : (byte)(i * 37);
}
var gamma = new byte[4];
BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455);
var png = TestImages.Png(("IHDR", TestImages.Ihdr(2, 2, 16, 2)), ("gAMA", gamma), ("sRGB", [0]), ("IDAT", TestImages.Zlib(raw)), ("IEND", []));
var info = PngDecoder.Identify(png);
Assert.AreEqual(16, info.BitsPerSample);
CollectionAssert.AreEqual(new[] { "gAMA", "sRGB" }, info.Metadata.ColorChunks.ToArray());
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
{
var result = ImageConverter.Convert(png, target);
var said = string.Join("; ", result.NotCarried);
Assert.IsTrue(result.Lossy, $"{target}: 16 bit diventano 8");
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("16 bit", StringComparison.Ordinal)), said);
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("gAMA", StringComparison.Ordinal)), said);
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("sRGB", StringComparison.Ordinal)), said);
}
// An 8-bit PNG without colour chunks converts losslessly and says nothing.
var plain = PngEncoder.Encode(TestImages.Random(5, 4, 2, opaque: true));
Assert.AreEqual(8, PngDecoder.Identify(plain).BitsPerSample);
var clean = ImageConverter.Convert(plain, ImageFormat.WebP);
Assert.IsFalse(clean.Lossy);
Assert.IsEmpty(clean.NotCarried);
// The precision of a 12-bit JPEG is reported too.
var twelve = JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [Enumerable.Repeat((ushort)1, 64).ToArray()], 0xC1);
Assert.AreEqual(12, JpegDecoder.Identify(JpegTestEncoder.Write(twelve, new JpegTestOptions())).BitsPerSample);
}
[TestMethod]
public void OnlyJpegPngAndWebPAreWritten()
{
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.Jpeg));
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.Png));
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.WebP));
Assert.IsFalse(ImageConverter.CanWrite(ImageFormat.Gif));
var png = PngEncoder.Encode(TestImages.Random(4, 4, 1));
Assert.ThrowsExactly<ArgumentException>(() => ImageConverter.Convert(png, ImageFormat.Gif));
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageConverter.Convert(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Png));
}
// ---- PNG texts ----
[TestMethod]
public void PngTextsAreWrittenAsTextOrInternationalText()
{
using var image = TestImages.Random(3, 3, 4);
var texts = new[]
{
new ImageText("Title", "Caffè"),
new ImageText("Comment", "Ελληνικά"),
new ImageText("Author", "Alberto", "it", "Autore"),
};
var png = PngEncoder.Encode(image, new PngEncoderOptions { Texts = texts });
var types = TestImages.PngChunks(png).Select(c => c.Type).ToArray();
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "tEXt", "iTXt", "iTXt", "IEND" }, types);
var info = PngDecoder.Identify(png);
CollectionAssert.AreEqual(texts, info.Metadata.Texts.ToArray());
}
[TestMethod]
public void PngKeywordsFollowTheSpecification()
{
Assert.IsTrue(PngEncoder.IsValidKeyword("Title"));
Assert.IsTrue(PngEncoder.IsValidKeyword(new string('k', 79)));
Assert.IsFalse(PngEncoder.IsValidKeyword(string.Empty));
Assert.IsFalse(PngEncoder.IsValidKeyword(new string('k', 80)));
Assert.IsFalse(PngEncoder.IsValidKeyword(" Title"));
Assert.IsFalse(PngEncoder.IsValidKeyword("Two spaces"));
Assert.IsFalse(PngEncoder.IsValidKeyword("Ελληνικά"));
using var image = TestImages.Random(2, 2, 1);
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { Texts = [new ImageText("", "x")] }));
}
// ---- Rasteriser ----
[TestMethod]
public void ACircleCoversItsArea()
{
foreach (var (cx, cy, r) in new[] { (32f, 32f, 20f), (31.3f, 30.7f, 9.5f), (40f, 24f, 2.5f) })
{
var covered = Coverage(64, 64, canvas => canvas.FillCircle(cx, cy, r, Color.White));
Assert.AreEqual(Math.PI * r * r, covered, Math.PI * r * r * 0.01, $"cerchio di raggio {r}");
}
}
[TestMethod]
public void ARectangleCoversExactlyItsPixels()
{
using var image = new RgbaImage(16, 16);
using (var canvas = new Canvas(image))
{
canvas.FillRect(3, 4, 5, 6, Color.White);
}
for (var y = 0; y < 16; y++)
{
for (var x = 0; x < 16; x++)
{
var inside = x is >= 3 and < 8 && y is >= 4 and < 10;
Assert.AreEqual(inside ? 255 : 0, image.GetPixel(x, y).A, $"({x}, {y})");
}
}
// Half a pixel in: the border pixels are half covered.
var half = Coverage(16, 16, canvas => canvas.FillRect(2.5f, 2.5f, 4, 4, Color.White));
Assert.AreEqual(16.0, half, 0.05);
}
[TestMethod]
public void ARotatedSquareKeepsItsArea()
{
var covered = Coverage(64, 64, canvas =>
{
canvas.Translate(32, 32);
canvas.Rotate(30);
canvas.FillRect(-12, -12, 24, 24, Color.White);
});
Assert.AreEqual(576.0, covered, 1.5);
}
[TestMethod]
public void ARingAndAHoleAreLeftEmptyInside()
{
var ring = Coverage(80, 80, canvas => canvas.StrokeCircle(40, 40, 25, 4, Color.White));
Assert.AreEqual(Math.PI * ((27.0 * 27) - (23.0 * 23)), ring, 6.0);
// A contour turning the other way inside another cuts a hole (non-zero rule); the same way, it adds nothing.
var hole = Coverage(40, 40, canvas => canvas.Fill(new PathBuilder().AddRect(5, 5, 30, 30).AddRect(15, 15, 10, 10, clockwise: false), Color.White));
Assert.AreEqual(800.0, hole, 0.5);
var same = Coverage(40, 40, canvas => canvas.Fill(new PathBuilder().AddRect(5, 5, 30, 30).AddRect(15, 15, 10, 10), Color.White));
Assert.AreEqual(900.0, same, 0.5);
}
[TestMethod]
public void ShapesOutsideTheCanvasAreClipped()
{
// A circle centred on the corner: a quarter of it is inside.
var covered = Coverage(32, 32, canvas => canvas.FillCircle(0, 0, 20, Color.White));
Assert.AreEqual(Math.PI * 400 / 4, covered, 4.0);
var nothing = Coverage(32, 32, canvas => canvas.FillCircle(-50, 10, 20, Color.White));
Assert.AreEqual(0.0, nothing);
}
[TestMethod]
public void AGradientRunsBetweenItsColours()
{
using var image = new RgbaImage(101, 4);
using (var canvas = new Canvas(image))
{
canvas.FillRect(0, 0, 101, 4, new LinearGradientBrush(new Vector2(0.5f, 0), new Vector2(100.5f, 0), [Color.Black, Color.White]));
}
Assert.IsLessThanOrEqualTo(1, (int)image.GetPixel(0, 2).R);
Assert.IsLessThanOrEqualTo(1, Math.Abs(image.GetPixel(50, 2).R - 128));
Assert.IsGreaterThanOrEqualTo(254, (int)image.GetPixel(100, 2).R);
for (var x = 1; x < 101; x++)
{
Assert.IsGreaterThanOrEqualTo((int)image.GetPixel(x - 1, 2).R, (int)image.GetPixel(x, 2).R, $"x = {x}");
}
}
[TestMethod]
public void HalfTransparentPaintMixesWithWhatIsBelow()
{
using var image = new RgbaImage(4, 4);
using (var canvas = new Canvas(image))
{
canvas.Clear(new Color(0, 0, 255));
canvas.FillRect(0, 0, 4, 4, new Color(255, 0, 0, 128));
}
var p = image.GetPixel(1, 1);
Assert.AreEqual(255, p.A);
Assert.IsLessThanOrEqualTo(1, Math.Abs(p.R - 128));
Assert.IsLessThanOrEqualTo(1, Math.Abs(p.B - 127));
}
// ---- helpers ----
private static RgbaImage Flat(int width, int height, byte r, byte g, byte b, byte a)
{
var image = new RgbaImage(width, height);
var pixels = image.Pixels;
for (var i = 0; i < pixels.Length; i += 4)
{
(pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]) = (r, g, b, a);
}
return image;
}
private static void AssertEveryPixel(RgbaImage image, (int R, int G, int B, int A) expected, int tolerance, string what)
{
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var p = image.GetPixel(x, y);
if (Math.Abs(p.R - expected.R) > tolerance || Math.Abs(p.G - expected.G) > tolerance
|| Math.Abs(p.B - expected.B) > tolerance || Math.Abs(p.A - expected.A) > tolerance)
{
Assert.Fail($"{what}: ({x}, {y}) è {p}, atteso {expected}");
}
}
}
}
/// <summary>Pixels covered by what <paramref name="draw"/> paints on a transparent canvas: the sum of alpha / 255.</summary>
private static double Coverage(int width, int height, Action<Canvas> draw)
{
using var image = new RgbaImage(width, height);
using (var canvas = new Canvas(image))
{
draw(canvas);
}
var sum = 0L;
var pixels = image.Pixels;
for (var i = 3; i < pixels.Length; i += 4)
{
sum += pixels[i];
}
return sum / 255.0;
}
/// <summary>A small big-endian TIFF block with one Orientation entry and one ASCII Make entry.</summary>
private static byte[] Tiff(ushort orientation)
{
var make = Encoding.ASCII.GetBytes("Febe\0");
var tiff = new byte[8 + 2 + (2 * 12) + 4 + make.Length];
"MM\0*"u8.CopyTo(tiff);
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(4), 8);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(8), 2);
var entry = tiff.AsSpan(10);
BinaryPrimitives.WriteUInt16BigEndian(entry, 0x010F); // Make
BinaryPrimitives.WriteUInt16BigEndian(entry[2..], 2); // ASCII
BinaryPrimitives.WriteUInt32BigEndian(entry[4..], (uint)make.Length);
BinaryPrimitives.WriteUInt32BigEndian(entry[8..], (uint)(tiff.Length - make.Length));
entry = tiff.AsSpan(22);
BinaryPrimitives.WriteUInt16BigEndian(entry, 0x0112); // Orientation
BinaryPrimitives.WriteUInt16BigEndian(entry[2..], 3); // SHORT
BinaryPrimitives.WriteUInt32BigEndian(entry[4..], 1);
BinaryPrimitives.WriteUInt16BigEndian(entry[8..], orientation);
make.CopyTo(tiff.AsSpan(tiff.Length - make.Length));
return tiff;
}
/// <summary>Bytes standing in for an ICC profile (the codecs carry it without reading it).</summary>
/// <summary>A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set.</summary>
private static byte[] Profile(int length, string colorSpace = "RGB ")
{
var bytes = new byte[length];
for (var i = 0; i < length; i++)
{
bytes[i] = (byte)((i * 7) + (i >> 3));
}
Encoding.ASCII.GetBytes(colorSpace, bytes.AsSpan(16, 4));
return bytes;
}
/// <summary>A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI.</summary>
private static byte[] WithIcc(byte[] jpeg, byte[] profile)
{
byte[] payload = [.. Encoding.ASCII.GetBytes("ICC_PROFILE"), 0, 1, 1, .. profile];
var segment = new byte[4 + payload.Length];
segment[0] = 0xFF;
segment[1] = 0xE2;
BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), (ushort)(payload.Length + 2));
payload.CopyTo(segment, 4);
return [.. jpeg.AsSpan(0, 2), .. segment, .. jpeg.AsSpan(2)];
}
}