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:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:02:03 +01:00
1 parent b4383a6110
commit d6a6a68496
47 files changed
+3391 -562

No files matched your search

+19 -15
View File
@@ -1,12 +1,12 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Images;
using Febe.Desktop.Core;
using Febe.Tests.Desktop.Support;
using SkiaSharp;
namespace Febe.Tests.Desktop;
/// <summary>
/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with SkiaSharp and written by the
/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with Febe's own canvas and written by the
/// hand-made ICO writer, at 16, 24, 32, 48, 64, 128 and 256 pixels. The committed <c>src/Febe.Desktop/Febe.ico</c> must be
/// what the code draws: <c>FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests</c> writes it again.
/// </summary>
@@ -53,28 +53,28 @@ public sealed class IconTests
{
using var image = IcoWriter.Decode(ico, entry);
var s = entry.Size;
Assert.AreEqual(0, image.GetPixel(0, 0).Alpha, $"{s}: transparent corner");
Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).Alpha, $"{s}: transparent corner");
Assert.AreEqual(0, image.GetPixel(0, 0).A, $"{s}: transparent corner");
Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).A, $"{s}: transparent corner");
// Inside the square, away from ring and moon (x=4/32, y=28/32): the accent colour #0F5C8C.
var accent = image.GetPixel(Scale(4, s), Scale(28, s));
if (s >= 24)
{
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), accent, 6, $"{s}: accent");
AssertClose(Accent, accent, 6, $"{s}: accent");
}
// The centre of the moon (23.2, 8.8) is white.
var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s));
if (s >= 32)
{
AssertClose(SKColors.White, moon, 10, $"{s}: moon");
AssertClose(White, moon, 10, $"{s}: moon");
}
// The centre of the ring (14.5, 17.5) is the accent, not white: it is a ring, not a disc.
var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s));
if (s >= 32)
{
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), hole, 6, $"{s}: ring hole");
AssertClose(Accent, hole, 6, $"{s}: ring hole");
}
}
}
@@ -82,8 +82,8 @@ public sealed class IconTests
[TestMethod]
public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge()
{
using var wide = new SKBitmap(32, 16);
using var huge = new SKBitmap(512, 512);
using var wide = new RgbaImage(32, 16);
using var huge = new RgbaImage(512, 512);
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([wide]));
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([huge]));
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([]));
@@ -106,7 +106,7 @@ public sealed class IconTests
var b = IcoWriter.ReadDirectory(fresh);
CollectionAssert.AreEqual(b.Select(e => e.Size).ToArray(), a.Select(e => e.Size).ToArray());
// Pixel by pixel, with a small tolerance (antialiasing may differ by a unit between SkiaSharp builds).
// Pixel by pixel, with a small tolerance (the drawing is in floating point).
for (var i = 0; i < a.Count; i++)
{
using var left = IcoWriter.Decode(committed, a[i]);
@@ -123,12 +123,16 @@ public sealed class IconTests
private static int Scale(double coordinate, int size) => Math.Clamp((int)Math.Floor(coordinate * size / 32), 0, size - 1);
private static void AssertClose(SKColor expected, SKColor actual, int tolerance, string what)
private static readonly (byte R, byte G, byte B, byte A) Accent = (0x0F, 0x5C, 0x8C, 0xFF);
private static readonly (byte R, byte G, byte B, byte A) White = (0xFF, 0xFF, 0xFF, 0xFF);
private static void AssertClose((byte R, byte G, byte B, byte A) expected, (byte R, byte G, byte B, byte A) actual, int tolerance, string what)
{
var ok = Math.Abs(expected.Red - actual.Red) <= tolerance
&& Math.Abs(expected.Green - actual.Green) <= tolerance
&& Math.Abs(expected.Blue - actual.Blue) <= tolerance
&& Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
var ok = Math.Abs(expected.R - actual.R) <= tolerance
&& Math.Abs(expected.G - actual.G) <= tolerance
&& Math.Abs(expected.B - actual.B) <= tolerance
&& Math.Abs(expected.A - actual.A) <= tolerance;
Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}");
}
}
@@ -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;
}
}
@@ -2,7 +2,6 @@ using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Import.Support;
@@ -244,7 +243,7 @@ internal static class ImportTestFiles
public static byte[] Cropped(int scene, int width, int height)
{
using var bitmap = TestImages.Scene(scene, width, height);
using var crop = TestImages.Crop(bitmap, new SKRectI(0, 0, width / 2, height / 2));
using var crop = TestImages.Crop(bitmap, 0, 0, width / 2, height / 2);
return TestImages.Jpeg(crop, 88);
}
+12 -12
View File
@@ -1,8 +1,8 @@
using System.Diagnostics;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Library;
@@ -15,7 +15,7 @@ public sealed class PerceptualHashTests
private static ulong Hash(byte[] encoded) => PerceptualHash.Compute(new MemoryStream(encoded)) ?? throw new AssertFailedException("Immagine non decodificata.");
private static ulong Hash(SKBitmap bitmap) => Hash(TestImages.Png(bitmap));
private static ulong Hash(RgbaImage image) => Hash(TestImages.Png(image));
/// <summary>
/// Calibration of <see cref="PerceptualHash.DuplicateThreshold"/> (spec §9.3, §14.1): resized and recompressed
@@ -63,20 +63,20 @@ public sealed class PerceptualHashTests
}
var side = Math.Min(width, height);
var crops = new (string Name, SKRectI Area)[]
var crops = new (string Name, (int Left, int Top, int Width, int Height) Area)[]
{
("centrale 80%", SKRectI.Create(width / 10, height / 10, width * 8 / 10, height * 8 / 10)),
("centrale 75%", SKRectI.Create(width / 8, height / 8, width * 3 / 4, height * 3 / 4)),
("centrale 60%", SKRectI.Create(width / 5, height / 5, width * 3 / 5, height * 3 / 5)),
("lato sinistro tolto 10%", SKRectI.Create(width / 10, 0, width * 9 / 10, height)),
("lato sinistro tolto 25%", SKRectI.Create(width / 4, 0, width * 3 / 4, height)),
("in alto tolto 33%", SKRectI.Create(0, height / 3, width, height * 2 / 3)),
("quadrato", SKRectI.Create((width - side) / 2, (height - side) / 2, side, side)),
("quarto in basso a destra", SKRectI.Create(width / 2, height / 2, width / 2, height / 2)),
("centrale 80%", (width / 10, height / 10, width * 8 / 10, height * 8 / 10)),
("centrale 75%", (width / 8, height / 8, width * 3 / 4, height * 3 / 4)),
("centrale 60%", (width / 5, height / 5, width * 3 / 5, height * 3 / 5)),
("lato sinistro tolto 10%", (width / 10, 0, width * 9 / 10, height)),
("lato sinistro tolto 25%", (width / 4, 0, width * 3 / 4, height)),
("in alto tolto 33%", (0, height / 3, width, height * 2 / 3)),
("quadrato", ((width - side) / 2, (height - side) / 2, side, side)),
("quarto in basso a destra", (width / 2, height / 2, width / 2, height / 2)),
};
foreach (var (name, area) in crops)
{
using var cropped = TestImages.Crop(scene, area);
using var cropped = TestImages.Crop(scene, area.Left, area.Top, area.Width, area.Height);
var distance = PerceptualHash.Distance(original, Hash(TestImages.Jpeg(cropped, 90)));
cropMin = Math.Min(cropMin, distance);
Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, ritaglio {name}: distanza {distance}");
+129 -10
View File
@@ -1,19 +1,24 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using Febe.Tests.Imaging;
using Febe.Tests.Support;
using SkiaSharp;
using TestImages = Febe.Tests.Support.TestImages;
namespace Febe.Tests.Library;
[TestClass]
public sealed class ThumbnailStoreTests
{
private static SKImageInfo InfoOf(string path)
private static ImageInfo InfoOf(string path)
{
using var codec = SKCodec.Create(path) ?? throw new AssertFailedException("Miniatura non leggibile.");
Assert.AreEqual(SKEncodedImageFormat.Jpeg, codec.EncodedFormat);
return codec.Info;
var info = ImageDecoder.Identify(File.ReadAllBytes(path));
Assert.AreEqual(ImageFormat.Jpeg, info.Format);
return info;
}
private static RgbaImage Read(string path) => ImageDecoder.Decode(File.ReadAllBytes(path));
[TestMethod]
public void ThumbnailsAre480PixelsOnTheLongSideStoredOnceAndSharded()
{
@@ -68,17 +73,90 @@ public sealed class ThumbnailStoreTests
Assert.AreEqual(360, info.Height);
}
[TestMethod]
public void UprightAndTaggedSidewaysGiveTheSameThumbnail()
{
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(4, 1200, 900);
using var sideways = TestImages.RotateCounterClockwise(scene);
Assert.IsTrue(store.Create(Make.Sha(9), new MemoryStream(TestImages.Png(scene))));
Assert.IsTrue(store.Create(Make.Sha(10), new MemoryStream(TestImages.WithExifOrientation(TestImages.Jpeg(sideways, 95), 6))));
using var upright = Read(store.PathFor(Make.Sha(9)));
using var turned = Read(store.PathFor(Make.Sha(10)));
var quality = ImageQuality.Compare(upright, turned);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void TransparentImagesBecomeJpegOnWhite()
{
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var transparent = new SKBitmap(new SKImageInfo(600, 600, SKColorType.Rgba8888, SKAlphaType.Premul));
transparent.Erase(SKColors.Transparent);
using var transparent = new RgbaImage(600, 600);
Assert.IsTrue(store.Create(Make.Sha(4), new MemoryStream(TestImages.Png(transparent))));
using var thumbnail = SKBitmap.Decode(store.PathFor(Make.Sha(4)));
using var thumbnail = Read(store.PathFor(Make.Sha(4)));
var pixel = thumbnail.GetPixel(10, 10);
Assert.IsGreaterThan((byte)240, pixel.Red);
Assert.IsGreaterThan((byte)240, pixel.R);
}
[TestMethod]
public void TheThumbnailShowsThePictureReducedFaithfully()
{
// Compared with the source reduced by area averaging (the most neutral reduction), what differs is only the
// JPEG compression and the filter.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(8, 2400, 1800);
Assert.IsTrue(store.Create(Make.Sha(7), new MemoryStream(TestImages.Png(scene))));
using var thumbnail = Read(store.PathFor(Make.Sha(7)));
using var expected = ImageResampler.Resize(scene, 480, 360, new ResampleOptions { Filter = ResampleFilter.Area });
var quality = ImageQuality.Compare(expected, thumbnail);
Assert.IsGreaterThan(28.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void AJpegShrunkWhileDecodingGivesTheSameThumbnailAsAFullDecode()
{
// 4000 × 3000 is decoded at a quarter (1000 × 750) and then reduced to 480: compared with the full-size path.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(9, 4000, 3000);
var jpeg = TestImages.Jpeg(scene, 92);
Assert.IsTrue(store.Create(Make.Sha(8), new MemoryStream(jpeg)));
using var thumbnail = Read(store.PathFor(Make.Sha(8)));
Assert.AreEqual((480, 360), (thumbnail.Width, thumbnail.Height));
using var full = ImageDecoder.Decode(jpeg);
using var reference = ImageResampler.Resize(full, 480, 360);
var quality = ImageQuality.Compare(reference, thumbnail);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void VideoFramesAsBmpBecomeThumbnails()
{
// The in-house video decoder (branch funzione/decoder-h264) hands frames over as 24-bit BMP, rows bottom up.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var frame = TestImages.Scene(11, 1280, 720);
Assert.IsTrue(store.Create(Make.Sha(11), new MemoryStream(Bmp24(frame))));
var info = InfoOf(store.PathFor(Make.Sha(11)));
Assert.AreEqual((480, 270), (info.Width, info.Height));
using var thumbnail = Read(store.PathFor(Make.Sha(11)));
using var expected = ImageResampler.Resize(frame, 480, 270);
var quality = ImageQuality.Compare(expected, thumbnail);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void ThePhotoOfASearchIsASmallJpeg()
{
using var scene = TestImages.Scene(12, 1080, 1080);
var small = ThumbnailStore.EncodeSmallJpeg(new MemoryStream(TestImages.Jpeg(scene)), 160);
Assert.IsNotNull(small);
var info = ImageDecoder.Identify(small);
Assert.AreEqual((ImageFormat.Jpeg, 160, 160), (info.Format, info.Width, info.Height));
Assert.IsNull(ThumbnailStore.EncodeSmallJpeg(new MemoryStream([1, 2, 3]), 160));
}
[TestMethod]
@@ -100,8 +178,14 @@ public sealed class ThumbnailStoreTests
var tile = store.NeutralVideoTile();
Assert.AreEqual(Path.Combine(temp.Path, ThumbnailStore.NeutralVideoTileName), tile);
var info = InfoOf(tile);
Assert.AreEqual(480, info.Height);
Assert.AreEqual((270, 480), (info.Width, info.Height));
Assert.AreEqual(tile, store.NeutralVideoTile());
// Light grey, a darker disc in the middle, the play sign in the light grey again.
using var image = Read(tile);
AssertGrey(image.GetPixel(10, 10), 0xE4, "sfondo");
AssertGrey(image.GetPixel(135 - 25, 240), 0x9A, "disco");
AssertGrey(image.GetPixel(135 + 2, 240), 0xE4, "segno di riproduzione");
}
[TestMethod]
@@ -140,4 +224,39 @@ public sealed class ThumbnailStoreTests
Assert.IsNull(await ffmpeg.ExtractJpegAsync(temp.Combine("non-esiste.mp4")));
}
private static void AssertGrey((byte R, byte G, byte B, byte A) pixel, int level, string what) =>
Assert.IsTrue(Math.Abs(pixel.R - level) <= 4 && Math.Abs(pixel.G - level) <= 4 && Math.Abs(pixel.B - level) <= 4, $"{what}: {pixel}");
/// <summary>A 24-bit BI_RGB BMP, rows bottom up, the way VideoImage.ToBmp writes it.</summary>
private static byte[] Bmp24(RgbaImage image)
{
var stride = ((image.Width * 3) + 3) & ~3;
var size = 54 + (stride * image.Height);
var bmp = new byte[size];
var span = bmp.AsSpan();
span[0] = (byte)'B';
span[1] = (byte)'M';
BinaryPrimitives.WriteInt32LittleEndian(span[2..], size);
BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54);
BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40);
BinaryPrimitives.WriteInt32LittleEndian(span[18..], image.Width);
BinaryPrimitives.WriteInt32LittleEndian(span[22..], image.Height);
BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1);
BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24);
BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * image.Height);
for (var y = 0; y < image.Height; y++)
{
var source = image.GetRow(y);
var target = span.Slice(54 + ((image.Height - 1 - y) * stride), image.Width * 3);
for (var x = 0; x < image.Width; x++)
{
target[x * 3] = source[(x * 4) + 2];
target[(x * 3) + 1] = source[(x * 4) + 1];
target[(x * 3) + 2] = source[x * 4];
}
}
return bmp;
}
}
+83 -66
View File
@@ -1,8 +1,10 @@
using System.Buffers.Binary;
using System.Numerics;
using Febe.Core.Abstractions;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Drawing;
using Febe.Data;
using SkiaSharp;
namespace Febe.Tests.Support;
@@ -116,37 +118,34 @@ internal static class TestDatabase
public static Task<FebeDatabase> OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name));
}
/// <summary>Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed.</summary>
/// <summary>
/// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed, drawn and encoded
/// with Febe's own code (Drawing, Codecs/Images).
/// </summary>
internal static class TestImages
{
public static SKBitmap Scene(int seed, int width = 1200, int height = 900)
public static RgbaImage Scene(int seed, int width = 1200, int height = 900)
{
var random = new Random(seed);
var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(bitmap);
SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
var image = new RgbaImage(width, height);
using var canvas = new Canvas(image);
Color RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
using (var background = new SKPaint())
{
var angle = random.NextDouble() * Math.PI * 2;
var dx = (float)Math.Cos(angle) * width / 2;
var dy = (float)Math.Sin(angle) * height / 2;
background.Shader = SKShader.CreateLinearGradient(
new SKPoint((width / 2f) - dx, (height / 2f) - dy),
new SKPoint((width / 2f) + dx, (height / 2f) + dy),
[RandomColor(), RandomColor(), RandomColor()],
null,
SKShaderTileMode.Clamp);
canvas.DrawRect(0, 0, width, height, background);
}
var angle = random.NextDouble() * Math.PI * 2;
var dx = (float)Math.Cos(angle) * width / 2;
var dy = (float)Math.Sin(angle) * height / 2;
var background = new LinearGradientBrush(
new Vector2((width / 2f) - dx, (height / 2f) - dy),
new Vector2((width / 2f) + dx, (height / 2f) + dy),
[RandomColor(), RandomColor(), RandomColor()]);
canvas.FillRect(0, 0, width, height, background);
using var paint = new SKPaint { IsAntialias = true };
var shapes = 10 + random.Next(10);
for (var i = 0; i < shapes; i++)
{
paint.Color = RandomColor().WithAlpha((byte)(160 + random.Next(96)));
paint.Style = random.Next(4) == 0 ? SKPaintStyle.Stroke : SKPaintStyle.Fill;
paint.StrokeWidth = 4 + random.Next(30);
var color = RandomColor().WithAlpha((byte)(160 + random.Next(96)));
var stroke = random.Next(4) == 0;
float strokeWidth = 4 + random.Next(30);
var x = (float)(random.NextDouble() * width);
var y = (float)(random.NextDouble() * height);
var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width);
@@ -154,76 +153,94 @@ internal static class TestImages
switch (random.Next(4))
{
case 0:
canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint);
if (stroke)
{
canvas.StrokeRect(x - (w / 2), y - (h / 2), w, h, strokeWidth, color);
}
else
{
canvas.FillRect(x - (w / 2), y - (h / 2), w, h, color);
}
break;
case 1:
canvas.DrawCircle(x, y, Math.Min(w, h) / 2, paint);
if (stroke)
{
canvas.StrokeCircle(x, y, Math.Min(w, h) / 2, strokeWidth, color);
}
else
{
canvas.FillCircle(x, y, Math.Min(w, h) / 2, color);
}
break;
case 2:
canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint);
if (stroke)
{
canvas.StrokeEllipse(x, y, w / 2, h / 2, strokeWidth, color);
}
else
{
canvas.FillEllipse(x, y, w / 2, h / 2, color);
}
break;
default:
paint.StrokeWidth = 6 + random.Next(20);
canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), paint);
strokeWidth = 6 + random.Next(20);
canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), strokeWidth, color);
break;
}
}
// Fine grain, as in a photo.
using var grain = new SKPaint { IsAntialias = false };
for (var i = 0; i < width * height / 60; i++)
{
var v = (byte)random.Next(256);
grain.Color = new SKColor(v, v, v, 28);
canvas.DrawPoint(random.Next(width), random.Next(height), grain);
canvas.BlendPixel(random.Next(width), random.Next(height), new Color(v, v, v, 28));
}
return bitmap;
return image;
}
public static byte[] Jpeg(SKBitmap bitmap, int quality = 90)
{
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality);
return data.ToArray();
}
public static byte[] Jpeg(RgbaImage image, int quality = 90) => JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality });
public static byte[] Png(SKBitmap bitmap)
{
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
return data.ToArray();
}
public static byte[] Png(RgbaImage image) => PngEncoder.Encode(image);
public static SKBitmap Resize(SKBitmap source, int width, int height)
public static RgbaImage Resize(RgbaImage source, int width, int height) => ImageResampler.Resize(source, width, height);
/// <summary>The pixels of <paramref name="width"/> × <paramref name="height"/> from (<paramref name="left"/>, <paramref name="top"/>).</summary>
public static RgbaImage Crop(RgbaImage source, int left, int top, int width, int height)
{
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
using var image = SKImage.FromBitmap(source);
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
var result = new RgbaImage(width, height);
for (var y = 0; y < height; y++)
{
source.GetRow(top + y).Slice(left * 4, width * 4).CopyTo(result.GetRow(y));
}
return result;
}
public static SKBitmap Crop(SKBitmap source, SKRectI area)
{
var result = new SKBitmap(new SKImageInfo(area.Width, area.Height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
using var image = SKImage.FromBitmap(source);
canvas.DrawImage(image, area, new SKRect(0, 0, area.Width, area.Height), new SKSamplingOptions(SKFilterMode.Nearest), null);
return result;
}
/// <summary>Decodes a JPEG/PNG back to a bitmap.</summary>
public static SKBitmap Decode(byte[] encoded) => SKBitmap.Decode(encoded) ?? throw new InvalidOperationException("decode");
/// <summary>Decodes a JPEG/PNG back to pixels (as stored: the orientation is not applied).</summary>
public static RgbaImage Decode(byte[] encoded) => ImageDecoder.Decode(encoded);
/// <summary>Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6).</summary>
public static SKBitmap RotateCounterClockwise(SKBitmap source)
public static RgbaImage RotateCounterClockwise(RgbaImage source)
{
var result = new SKBitmap(new SKImageInfo(source.Height, source.Width, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
canvas.Translate(0, source.Width);
canvas.RotateDegrees(-90);
canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
var result = new RgbaImage(source.Height, source.Width);
for (var y = 0; y < result.Height; y++)
{
var row = result.GetRow(y);
for (var x = 0; x < result.Width; x++)
{
// Target (x, y) shows source (w − 1 − y, x).
var (r, g, b, a) = source.GetPixel(source.Width - 1 - y, x);
row[x * 4] = r;
row[(x * 4) + 1] = g;
row[(x * 4) + 2] = b;
row[(x * 4) + 3] = a;
}
}
return result;
}