Codec di casa al posto di SkiaSharp (C1, passo 5)
SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies escono da Directory.Packages.props e da ogni progetto, per la regola «niente componenti esterni». Tutto ciò che leggeva, ridimensionava o disegnava immagini con Skia ora usa codice scritto in casa sulla BCL: - ImageResampler: Lanczos3 separabile o media per area, alfa premoltiplicata, luce lineare facoltativa; ImageGray per l'impronta. - Il lettore JPEG decodifica ridotto a 1/2, 1/4, 1/8; le miniature chiedono almeno il doppio del lato lungo, così l'ultimo passo resta a Lanczos e la miniatura resta uguale alla lettura intera. - ImageOrientation applica l'EXIF in un punto solo (miniature, impronte, anteprime, dimensioni mostrate). - ImageConverter cambia formato fra JPEG, PNG e WebP portando EXIF, ICC, XMP e testi, con l'etichetta d'orientamento e i pixel non ruotati; PngEncoder scrive anche i testi (tEXt o iTXt). - Febe.Core.Drawing: rasterizzatore con antialiasing (tracciati, riempimenti, tratti, gradienti) per icona, immagini dimostrative, riquadro neutro dei video, foto del sito di prova e prove. Febe.ico rigenerata. - ThumbnailStore legge anche i BMP a 24 bit, come quelli del decoder video del ramo funzione/decoder-h264. Le impronte salvate restano confrontabili (390 su 393 campioni identiche, le altre a distanza 2, soglia 6): nessun ricalcolo. Un PNG o JPEG troncato ora non ha miniatura né impronta. Documenti, elenco dei componenti della pagina «Informazioni» e decisioni aggiornati; nuove prove per ridimensionamento, orientamento, lettura ridotta, conversione con metadati, testi PNG e rasterizzatore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b4383a6110
commit
d6a6a68496
47 files changed
+3391
-562
No files matched your search
@@ -0,0 +1,528 @@
|
||||
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 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 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>
|
||||
private static byte[] Profile(int length)
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
bytes[i] = (byte)((i * 7) + (i >> 3));
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user