diff --git a/Directory.Packages.props b/Directory.Packages.props
index bd954cc..6a048c4 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -2,8 +2,6 @@
-
-
diff --git a/docs/decisioni.md b/docs/decisioni.md
index a88a50d..ed3a59d 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -424,3 +424,11 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Base dei codec d'immagine di casa in `src/Febe.Core/Codecs/Images` (spazio dei nomi `Febe.Core.Codecs.Images`, accanto a `Codecs/Containers` del ramo `funzione/decoder-h264`): `RgbaImage` (RGBA a 8 bit non premoltiplicata, array suo o preso dal pool e reso con `Dispose`), `ImageLimits` (predefiniti 65535 pixel per lato, 100 milioni di pixel come `ImageDecoding.MaxDecodedPixels`, 512 MiB di memoria di lavoro, 16 MiB di metadati decompressi), `ImageDecodeException` con `ImageLimitException` e `ImageFormatNotSupportedException`, `ImageFormatSniffer`, la facciata `ImageDecoder`; lettore e scrittore PNG, lettori GIF e BMP dalle specifiche, CRC-32 e LZW scritti in casa, zlib di `System.IO.Compression`. Scelte di lettura: i campioni a 16 bit tengono il byte alto e le maschere BMP sotto gli 8 bit si scalano con arrotondamento (così i 37 riferimenti PNG, GIF e BMP coincidono byte per byte); nessuna gestione del colore (profilo ICC, gamma); un blocco PNG ausiliario con il CRC sbagliato si salta, uno critico ferma la lettura; un PNG senza `IEND` dopo dati completi si accetta, uno tagliato prima no; un GIF tagliato o con dati LZW rotti dà ciò che si è letto, il resto trasparente; del GIF solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo, più il numero dei fotogrammi; nel BMP l'alfa viene solo da una maschera alfa di `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, i pixel saltati da RLE restano trasparenti, `BI_PNG` passa al lettore PNG, `BI_JPEG` e 64 bit non si leggono. `Identify` legge misura, fotogrammi e metadati senza applicare i limiti di misura; `Decode` li applica prima di allocare. Lo scrittore PNG scrive RGB o RGBA a 8 bit (RGB in automatico se tutto è opaco), per ogni riga il filtro con la minima somma dei valori assoluti (specifica PNG §12.8), `IDAT` da 64 KiB e, a richiesta, `eXIf`, `iCCP` e l'XMP in un `iTXt` | C1: SkiaSharp esce da Febe e niente componenti esterni (decisione di Alberto del 18 novembre 2026). Lettori tolleranti dove lo sono i browser (GIF, metadati), severi dove un'immagine letta a metà passerebbe per buona (PNG, BMP); limiti controllati prima di ogni allocazione, perché pochi byte di un file possono chiedere gigabyte |
| 2026-11-18 | Lettore e scrittore JPEG di casa (`JpegDecoder`, `JpegEncoder`), scritti dalla T.81: il lettore fa sequenziale di base ed esteso, progressivo, senza perdita, con Huffman e con codifica aritmetica, a 8 e 12 bit (senza perdita da 2 a 16), qualunque campionamento, ripristino, DNL; IDCT esatta in virgola mobile e crominanza con il filtro triangolare dove il rapporto è 2; colori secondo JFIF, Adobe APP14 (CMYK e YCCK invertiti come li scrive Adobe) e identificatori `R`, `G`, `B`; tabelle dell'allegato K quando manca `DHT` (Motion JPEG); dati troncati dentro una scansione = file danneggiato, EOI mancante e byte dopo EOI accettati; gerarchici e JPEG a 2 componenti rifiutati come formato non letto. L'orientamento EXIF va in `ImageMetadata.Orientation` e non si applica ai pixel. Lo scrittore fa solo il sequenziale di base (qualità 1–100 sulle tabelle dell'allegato K, 4:2:0 e 4:4:4, grigio, ripristino) con EXIF, ICC a pezzi, XMP e commenti. Progressivo, aritmetico, 12 bit e senza perdita si provano con un codificatore di prova (`tests/Febe.Tests/Imaging/JpegTestEncoder.cs`) confrontando i coefficienti con la codifica di base; contro SkiaSharp la tolleranza è PSNR ≥ 40 dB per canale e ≤ 0,1% di pixel con scarto oltre 16 | Tappa C1, passo 3: niente componenti esterni (decisione del 18 novembre 2026). Due lettori JPEG corretti differiscono per gli arrotondamenti, quindi contro il riferimento serve una soglia; il nostro sta fra 59 e 67 dB. La codifica aritmetica è verificata solo con il nostro codificatore e le tabelle della specifica: nessun file di riferimento esterno |
| 2026-11-18 | Lettore e scrittore WebP di casa (`WebPDecoder`, `WebPEncoder`), scritti dalla RFC 9649 e, per VP8, dalla RFC 6386: il lettore fa VP8 con perdita (decodificatore booleano, segmenti, modi intra, DCT e WHT, filtro semplice e normale, più partizioni), VP8L senza perdita (codici prefissi, cache dei colori, le quattro trasformate), `ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF (tolto il prefisso «Exif» se c'è) e XMP; di un'animazione solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo di `ANIM`, con lo scostamento di `ANMF` e la fusione della specifica, più il numero dei fotogrammi. Scelte di lettura: YUV→RGB BT.601 a intervallo ridotto in virgola fissa a 16 bit e crominanza ricampionata con i pesi 9/3/3/1 (così i quattro riferimenti con perdita stanno fra 68,7 e 74,4 dB, scarto massimo 1, alfa esatta; i quattro senza perdita coincidono); severo dove un'immagine letta a metà passerebbe per buona: dimensione RIFF oltre il file, blocco oltre la fine, tela diversa dall'immagine, trasformata ripetuta, codice prefisso incompleto, distanza prima dell'inizio, dati VP8 finiti prima dell'ultimo macroblocco (si tollera un solo byte di riempimento a zero, perché il codificatore booleano chiude con byte che il lettore può non usare), `ALPH` corto o con bit riservati; i modi 14 e 15 del predittore VP8L, non definiti, valgono come 0. Lo scrittore fa solo VP8L senza perdita (tavolozza fino a 256 colori, sottrazione del verde, predittore per blocchi, trasformata del colore, LZ77 con catene di hash, cache dei colori scelta stimando l'entropia, codici di Huffman limitati a 15 bit) e il formato esteso VP8X solo se ci sono metadati, nell'ordine VP8X, ICCP, VP8L, EXIF, XMP | Tappa C1, passo 4: niente componenti esterni (decisione del 18 novembre 2026). Uno scrittore con perdita servirebbe solo a file più piccoli, e la libreria conserva gli originali: senza perdita i 57 riferimenti stanno all'88% del PNG di casa, e sul riferimento grande 70952 byte contro i 64406 di libwebp |
+| 2026-11-18 | SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies tolti da `Directory.Packages.props` e da ogni progetto (C1, passo 5): miniature, impronte, anteprime dell'importazione, icona, immagini dimostrative, riquadro neutro dei video, foto del sito di prova e aiuti delle prove usano i codec di casa e `Febe.Core.Drawing` | Regola «niente componenti esterni» del 18 novembre 2026; l'elenco chiuso di §3 si riduce a Microsoft.Data.Sqlite, Microsoft.Web.WebView2 e MSTest. Il Dockerfile non aveva librerie native solo per Skia (il pacchetto NoDependencies non ne chiedeva): restano quelle di .NET e di Chromium |
+| 2026-11-18 | Ridimensionamento di casa (`ImageResampler`): filtro separabile Lanczos3 allargato del rapporto di riduzione, o media per area esatta; alfa premoltiplicata quando l'immagine non è opaca (il colore si divide per l'alfa filtrata prima di limitarla), luce lineare facoltativa con tabelle sRGB; righe filtrate in orizzontale tenute in un anello, `Vector4`, nessuna allocazione per pixel | Qualità almeno pari al filtro di Skia senza dipendere da lui; la luce lineare resta spenta per le miniature, come prima |
+| 2026-11-18 | Il lettore JPEG decodifica anche ridotto a 1/2, 1/4, 1/8 (`JpegDecoder.DecodeReduced`, `ImageDecoder.DecodeAtLeast`): ogni blocco trasformato intero e mediato, a 1/8 il solo coefficiente DC. Le miniature chiedono almeno il doppio del lato lungo (960 per 480), le impronte almeno 256 | Una foto da 12 MP si legge a un quarto dei pixel. Il doppio e non il lato esatto: a 1/8 le medie dei blocchi 8 × 8 si vedevano, quasi 1:1, sotto i 30 dB contro la lettura intera |
+| 2026-11-18 | Disegnatore di casa `Febe.Core.Drawing` (`Canvas`, `PathBuilder`, `SolidBrush`, `LinearGradientBrush`, `Matrix2D`): rasterizzatore ad area con segno, regola non-zero, curve spezzate entro 0,01 pixel, riempimenti, tratti con estremi tondi, gradienti lineari, cerchi sfumati con erfc, fusione «sopra» in alfa non premoltiplicata. Nessun testo e nessun carattere | Serve solo a icona, immagini dimostrative, riquadro dei video, foto del sito di prova e prove: nessuno di questi scrive testo, quindi niente caratteri di terzi |
+| 2026-11-18 | Orientamento EXIF applicato in un punto solo (`ImageOrientation.Apply`, da `ImageDecoding.DecodeUpright`) per miniature, impronte, anteprime e dimensioni mostrate; `ImageConverter` cambia formato (JPEG, PNG, WebP) portando EXIF, ICC e XMP, i testi in blocchi PNG o commenti JPEG, e tiene l'etichetta d'orientamento senza ruotare i pixel; ciò che non entra nel formato d'arrivo lo elenca in `NotCarried` | Per le esportazioni (#58): stessa foto, altra estensione. Ruotare i pixel e insieme tenere l'etichetta la ruoterebbe due volte |
+| 2026-11-18 | Impronte percettive già salvate: restano confrontabili, nessun ricalcolo. Misurato prima di togliere Skia su 393 campioni (scene a 7 misure fino a 4000×3000 e 3024×4032 in JPEG q92 e q70, PNG, WebP q80, più i 57 file di riferimento): 390 impronte identiche, 3 a distanza 2, soglia dei doppioni 6 | Stesso algoritmo (luma su bianco con pesi BT.601, media per area a 32×32 in double, DCT 8×8, mediana); cambia solo il lettore |
+| 2026-11-18 | Un PNG o un JPEG troncato ora non dà miniatura né impronta (il file si importa lo stesso, con SHA-256, nome e date) | SkiaSharp teneva l'immagine a metà («IncompleteInput»); i lettori di casa la rifiutano, come per gli altri file rovinati, e una miniatura a metà non è la foto |
+| 2026-11-18 | `Febe.ico` ridisegnata dal disegnatore di casa e rigenerata; `tools/Febe.SitoDiProva` ora fa riferimento a `Febe.Core` per disegnare e codificare le foto finte | Le stesse forme del marchio (appendice C), con un rasterizzatore diverso: la prova dell'icona le confronta con il disegno. Il sito di prova non aveva altro modo di fare JPEG senza Skia |
diff --git a/docs/docker.md b/docs/docker.md
index c74528d..57c2e11 100644
--- a/docs/docker.md
+++ b/docs/docker.md
@@ -12,7 +12,10 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b
- Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona.
- Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET.
- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati), ICU, caratteri di sistema con le emoji
- (`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata.
+ (`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`, per Chromium), certificati, `tzdata`, la lingua
+ `it_IT.UTF-8` generata.
+- Nessuna libreria per le immagini: miniature, impronte e disegni li fanno i codec di Febe scritti in C#
+ (`src/Febe.Core/Codecs/Images`, `src/Febe.Core/Drawing`).
- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per
scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium.
- Un file di criteri di Chromium (`/etc/chromium/policies/managed/febe.json`) che spegne il salvataggio delle password e
diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md
index 9dd2176..30068f4 100644
--- a/docs/guida/Sviluppo.md
+++ b/docs/guida/Sviluppo.md
@@ -9,8 +9,10 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres
- **Nessuna prova, script o verifica contatta Instagram** (né Meta, né il loro CDN): si usa solo il sito di prova
locale. Le prove dal vivo le lancia Alberto. Lo stesso vale per **Telegram**: le prove usano un gestore HTTP finto,
mai `api.telegram.org`.
-- **Dipendenze a elenco chiuso** (`Directory.Packages.props`): Microsoft.Data.Sqlite, SkiaSharp (con le librerie native
- per Linux), Microsoft.Web.WebView2, MSTest. Tutto il resto viene dalla libreria di base di .NET.
+- **Dipendenze a elenco chiuso** (`Directory.Packages.props`): Microsoft.Data.Sqlite, Microsoft.Web.WebView2, MSTest.
+ Tutto il resto viene dalla libreria di base di .NET o è scritto in casa: le immagini (PNG, JPEG, GIF, BMP, WebP) le
+ leggono e scrivono codec di Febe (`src/Febe.Core/Codecs/Images`), e icona, immagini dimostrative e riquadri li
+ disegna `src/Febe.Core/Drawing`.
## Com'è fatto il repository
diff --git a/docs/windows.md b/docs/windows.md
index 086373c..201ba67 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -46,8 +46,8 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i
dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la
libreria in `Immagini\Febe`, finché non scegli altre cartelle.
-`Febe.exe` è un file solo (circa 86 MB): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite, SkiaSharp,
-WebView2Loader). Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale.
+`Febe.exe` è un file solo (circa 86 MB): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite,
+WebView2Loader). Le immagini le leggono, le scrivono e le disegnano codec di Febe scritti in C#. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale.
## Il primo collegamento a Instagram
@@ -229,7 +229,7 @@ controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il
`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`).
L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con
-SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio,
+il disegnatore di casa (`Febe.Core.Drawing`) e scritta a mano: per rigenerarla dopo un cambio del marchio,
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
## Prove automatiche su Windows
diff --git a/src/Febe.Core/Codecs/Images/ImageConverter.cs b/src/Febe.Core/Codecs/Images/ImageConverter.cs
new file mode 100644
index 0000000..89d71b0
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageConverter.cs
@@ -0,0 +1,220 @@
+using System.Text;
+
+namespace Febe.Core.Codecs.Images;
+
+/// Options of .
+public sealed record ImageConversionOptions
+{
+ /// The options used when a caller passes none.
+ public static ImageConversionOptions Default { get; } = new();
+
+ /// Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026).
+ public int JpegQuality { get; init; } = 92;
+
+ /// Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible.
+ public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444;
+
+ /// What transparent areas become in a JPEG target, which has no alpha.
+ public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White;
+
+ /// Limits of the decoding of the source.
+ public ImageLimits Limits { get; init; } = ImageLimits.Default;
+}
+
+/// What made.
+/// The converted file.
+/// The format of the source.
+/// The format written.
+/// Width as stored (the orientation is not applied: the tag is copied).
+/// Height as stored.
+/// Whether pixels may differ from the source's (a JPEG target).
+/// The metadata written.
+/// What of the source's metadata the target could not take, in Italian, for the interface.
+public sealed record ImageConversionResult(
+ byte[] Data,
+ ImageFormat Source,
+ ImageFormat Target,
+ int Width,
+ int Height,
+ bool Lossy,
+ ImageMetadata Metadata,
+ IReadOnlyList NotCarried);
+
+///
+/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
+/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP losslessly, JPEG at
+/// the quality of the options. The EXIF block (dates, camera, the orientation tag), the ICC profile and the XMP
+/// packet are copied as they are; the pixels stay as stored, not turned by the orientation, which the copied tag
+/// still describes. Texts go where the target can hold them: PNG text chunks, JPEG comments; WebP has none, and
+/// what cannot be carried is listed in . Animations keep their first
+/// frame only, and say so.
+///
+public static class ImageConverter
+{
+ /// The formats a conversion can write.
+ public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
+
+ /// Converts (any format reads) to .
+ /// The target is not JPEG, PNG or WebP.
+ /// The source is damaged, too large or in a format Febe does not read.
+ public static ImageConversionResult Convert(ReadOnlyMemory source, ImageFormat target, ImageConversionOptions? options = null)
+ {
+ if (!CanWrite(target))
+ {
+ throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
+ }
+
+ options ??= ImageConversionOptions.Default;
+ using var image = ImageDecoder.Decode(source, out var info, options.Limits, pooled: true);
+ var notCarried = new List();
+ if (info.FrameCount > 1)
+ {
+ notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}");
+ }
+
+ var metadata = info.Metadata;
+ var exif = metadata.Exif;
+ var icc = metadata.IccProfile;
+ var xmp = metadata.Xmp;
+ var texts = metadata.Texts;
+ byte[] data;
+ switch (target)
+ {
+ case ImageFormat.Png:
+ data = PngEncoder.Encode(image, new PngEncoderOptions
+ {
+ Exif = exif,
+ IccProfile = icc,
+ IccProfileName = ValidIccName(metadata.IccProfileName) ?? PngEncoderOptions.Default.IccProfileName,
+ Xmp = xmp,
+ Texts = PngTexts(texts, notCarried),
+ });
+ break;
+ case ImageFormat.WebP:
+ if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
+ {
+ throw new ImageLimitException($"Un'immagine WebP non supera {WebPEncoder.MaxDimension} pixel per lato ({image.Width}×{image.Height}).");
+ }
+
+ if (texts.Count > 0)
+ {
+ notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
+ }
+
+ data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
+ break;
+ default:
+ {
+ if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
+ {
+ notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
+ exif = null;
+ }
+
+ if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
+ {
+ notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
+ xmp = null;
+ }
+
+ var comments = new List();
+ foreach (var text in texts)
+ {
+ comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
+ }
+
+ if (!image.IsOpaque())
+ {
+ ImageBackground.Flatten(image, options.JpegBackground);
+ notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
+ }
+
+ data = JpegEncoder.Encode(image, new JpegEncoderOptions
+ {
+ Quality = options.JpegQuality,
+ Subsampling = options.JpegSubsampling,
+ Exif = exif,
+ IccProfile = icc,
+ Xmp = xmp,
+ Comments = comments,
+ });
+ break;
+ }
+ }
+
+ var written = new ImageMetadata
+ {
+ Exif = exif,
+ Orientation = metadata.Orientation,
+ IccProfile = icc,
+ IccProfileName = metadata.IccProfileName,
+ Xmp = xmp,
+ Texts = target == ImageFormat.WebP ? [] : texts,
+ };
+ return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, target == ImageFormat.Jpeg, written, notCarried);
+ }
+
+ /// Bytes of payload in one JPEG marker segment (65535 less the two of the length).
+ private const int JpegMaxSegmentPayload = 65533;
+
+ private static string? ValidIccName(string? name)
+ {
+ if (string.IsNullOrEmpty(name) || name.Length > 79)
+ {
+ return null;
+ }
+
+ foreach (var c in name)
+ {
+ if (c < 32 || c > 255 || (c > 126 && c < 161))
+ {
+ return null;
+ }
+ }
+
+ return name.Trim().Length == name.Length ? name : null;
+ }
+
+ private static List PngTexts(IReadOnlyList texts, List notCarried)
+ {
+ var result = new List(texts.Count);
+ foreach (var text in texts)
+ {
+ var keyword = text.Keyword.Length == 0 ? "Comment" : text.Keyword;
+ if (!PngEncoder.IsValidKeyword(keyword))
+ {
+ notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
+ continue;
+ }
+
+ result.Add(text with { Keyword = keyword });
+ }
+
+ return result;
+ }
+}
+
+/// Composites an image over a plain colour.
+public static class ImageBackground
+{
+ /// Every pixel of seen over , opaque, in place.
+ public static void Flatten(RgbaImage image, Drawing.Color background)
+ {
+ ArgumentNullException.ThrowIfNull(image);
+ var pixels = image.Pixels;
+ for (var i = 0; i < pixels.Length; i += 4)
+ {
+ int a = pixels[i + 3];
+ if (a == 255)
+ {
+ continue;
+ }
+
+ var keep = 255 - a;
+ pixels[i] = (byte)(((pixels[i] * a) + (background.R * keep) + 127) / 255);
+ pixels[i + 1] = (byte)(((pixels[i + 1] * a) + (background.G * keep) + 127) / 255);
+ pixels[i + 2] = (byte)(((pixels[i + 2] * a) + (background.B * keep) + 127) / 255);
+ pixels[i + 3] = 255;
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs
index d653068..372eaf2 100644
--- a/src/Febe.Core/Codecs/Images/ImageDecoder.cs
+++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs
@@ -38,6 +38,53 @@ public static class ImageDecoder
var other => throw NotSupported(other),
};
+ /// Decodes an image to straight RGBA8 and returns what returns as well.
+ /// The format is not known or has no decoder yet.
+ /// The file is damaged.
+ /// The image is larger than allow.
+ public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ switch (ImageFormatSniffer.Detect(data.Span))
+ {
+ case ImageFormat.Png:
+ return PngDecoder.Decode(data, out info, limits, pooled);
+ case ImageFormat.Jpeg:
+ return JpegDecoder.Decode(data, out info, limits, pooled);
+ case ImageFormat.Gif:
+ return GifDecoder.Decode(data, out info, limits, pooled);
+ case ImageFormat.Bmp:
+ return BmpDecoder.Decode(data, out info, limits, pooled);
+ case ImageFormat.WebP:
+ return WebPDecoder.Decode(data, out info, limits, pooled);
+ case var other:
+ throw NotSupported(other);
+ }
+ }
+
+ ///
+ /// Decodes an image no smaller than on its long side where the format allows a
+ /// cheaper reduced decode (JPEG: a half, a quarter or an eighth, the smallest that keeps that side), at full size
+ /// otherwise; with what returns (the full size). The result may still need resizing.
+ ///
+ public static RgbaImage DecodeAtLeast(ReadOnlyMemory data, int minLongSide, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(minLongSide);
+ if (ImageFormatSniffer.Detect(data.Span) != ImageFormat.Jpeg)
+ {
+ return Decode(data, out info, limits, pooled);
+ }
+
+ var header = JpegDecoder.Identify(data, limits);
+ var longSide = Math.Max(header.Width, header.Height);
+ var reduction = 0;
+ while (reduction < 3 && ((longSide + (2 << reduction) - 1) >> (reduction + 1)) >= minLongSide)
+ {
+ reduction++;
+ }
+
+ return JpegDecoder.DecodeReduced(data, reduction, out info, limits, pooled);
+ }
+
private static ImageFormatNotSupportedException NotSupported(ImageFormat format) =>
format == ImageFormat.Unknown
? new ImageFormatNotSupportedException("Formato d'immagine non riconosciuto.")
diff --git a/src/Febe.Core/Codecs/Images/ImageGray.cs b/src/Febe.Core/Codecs/Images/ImageGray.cs
new file mode 100644
index 0000000..838ab56
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageGray.cs
@@ -0,0 +1,33 @@
+namespace Febe.Core.Codecs.Images;
+
+/// Grey levels of RGBA pixels.
+public static class ImageGray
+{
+ ///
+ /// The grey level 0-255 of each pixel of an RGBA row seen over white, with the weights of ITU-R BT.601
+ /// (0.299 R + 0.587 G + 0.114 B): a transparent pixel is white, a half-transparent one halfway to white.
+ ///
+ public static void LumaOverWhite(ReadOnlySpan rgba, Span output)
+ {
+ if (output.Length * 4 > rgba.Length)
+ {
+ throw new ArgumentException("The row has fewer pixels than the output.", nameof(rgba));
+ }
+
+ for (var x = 0; x < output.Length; x++)
+ {
+ var i = x * 4;
+ int a = rgba[i + 3];
+ if (a == 255)
+ {
+ output[x] = (0.299 * rgba[i]) + (0.587 * rgba[i + 1]) + (0.114 * rgba[i + 2]);
+ continue;
+ }
+
+ // Over white each channel becomes c·α + 255·(1 − α), with α = a / 255.
+ var alpha = a / 255.0;
+ var white = 255 - a;
+ output[x] = (0.299 * ((rgba[i] * alpha) + white)) + (0.587 * ((rgba[i + 1] * alpha) + white)) + (0.114 * ((rgba[i + 2] * alpha) + white));
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageOrientation.cs b/src/Febe.Core/Codecs/Images/ImageOrientation.cs
new file mode 100644
index 0000000..0220f31
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageOrientation.cs
@@ -0,0 +1,70 @@
+namespace Febe.Core.Codecs.Images;
+
+///
+/// The eight EXIF orientations (TIFF 6.0, tag 0x0112): how the stored pixels must be turned to be shown upright.
+/// 1 upright; 2 mirrored left-right; 3 turned 180°; 4 mirrored top-bottom; 5 mirrored along the main diagonal
+/// (transposed); 6 to be turned 90° clockwise; 7 mirrored along the other diagonal; 8 to be turned 90° anticlockwise.
+/// The decoders report the orientation and never apply it: only what Febe shows (thumbnails, previews, the perceptual
+/// hash) is turned; files and conversions keep the stored pixels and the tag.
+///
+public static class ImageOrientation
+{
+ /// Whether the orientation swaps width and height (5-8).
+ public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8;
+
+ /// The size of an image as shown, from its stored size.
+ public static (int Width, int Height) ShownSize(int width, int height, int orientation) =>
+ SwapsAxes(orientation) ? (height, width) : (width, height);
+
+ ///
+ /// The image turned upright. Returns itself for orientation 1 (or any value outside
+ /// 1-8); otherwise a new image (pooled when asked), and is left as it is.
+ ///
+ public static RgbaImage Apply(RgbaImage stored, int orientation, bool pooled = false)
+ {
+ ArgumentNullException.ThrowIfNull(stored);
+ if (orientation is < 2 or > 8)
+ {
+ return stored;
+ }
+
+ var w = stored.Width;
+ var h = stored.Height;
+ var (ow, oh) = ShownSize(w, h, orientation);
+ var result = pooled ? RgbaImage.Rent(ow, oh) : new RgbaImage(ow, oh);
+ var source = stored.Pixels;
+ var target = result.Pixels;
+ var sourceStride = w * 4;
+
+ // For every target pixel (x, y) the stored pixel it shows: sx = x0 + x·dxx + y·dxy, sy = y0 + x·dyx + y·dyy.
+ var (x0, dxx, dxy, y0, dyx, dyy) = orientation switch
+ {
+ 2 => (w - 1, -1, 0, 0, 0, 1),
+ 3 => (w - 1, -1, 0, h - 1, 0, -1),
+ 4 => (0, 1, 0, h - 1, 0, -1),
+ 5 => (0, 0, 1, 0, 1, 0),
+ 6 => (0, 0, 1, h - 1, -1, 0),
+ 7 => (w - 1, 0, -1, h - 1, -1, 0),
+ _ => (w - 1, 0, -1, 0, 1, 0), // 8
+ };
+
+ var step = (dyx * sourceStride) + (dxx * 4);
+ for (var y = 0; y < oh; y++)
+ {
+ var sx = x0 + (y * dxy);
+ var sy = y0 + (y * dyy);
+ var s = (sy * sourceStride) + (sx * 4);
+ var row = target.Slice(y * ow * 4, ow * 4);
+ for (var x = 0; x < row.Length; x += 4)
+ {
+ row[x] = source[s];
+ row[x + 1] = source[s + 1];
+ row[x + 2] = source[s + 2];
+ row[x + 3] = source[s + 3];
+ s += step;
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageResampler.cs b/src/Febe.Core/Codecs/Images/ImageResampler.cs
new file mode 100644
index 0000000..cbdd54d
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageResampler.cs
@@ -0,0 +1,433 @@
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Febe.Core.Codecs.Images;
+
+/// The filter weighs the source pixels with.
+public enum ResampleFilter
+{
+ ///
+ /// The Lanczos window of three lobes, sinc(x) sinc(x/3) for |x| < 3: sharp, with a faint ring along hard edges.
+ /// When reducing, the window is stretched by the reduction so that every source pixel counts (no aliasing).
+ ///
+ Lanczos3,
+
+ ///
+ /// Area averaging when reducing: each target pixel is the mean of the source area it covers, partial pixels
+ /// weighted by the fraction covered. Enlarging falls back to linear interpolation.
+ ///
+ Area,
+}
+
+/// Options of .
+public sealed record ResampleOptions
+{
+ /// The options used when a caller passes none.
+ public static ResampleOptions Default { get; } = new();
+
+ public ResampleFilter Filter { get; init; } = ResampleFilter.Lanczos3;
+
+ ///
+ /// Average the light rather than the stored values: sRGB samples are turned into linear light before filtering and
+ /// back afterwards. Off by default, as other programs resize (thin bright lines on dark keep more of their weight
+ /// when on).
+ ///
+ public bool LinearLight { get; init; }
+}
+
+///
+/// Changes the size of an image with a separable filter: every row is filtered horizontally into a short ring of
+/// floating-point rows, and each target row is a weighted sum of the ring's rows. Memory is the target image plus
+/// a few rows, whatever the size of the source. Images with transparency are filtered with premultiplied alpha, so
+/// the colour under transparent pixels does not bleed into the visible ones.
+///
+public static class ImageResampler
+{
+ /// resized to × .
+ public static RgbaImage Resize(RgbaImage source, int width, int height, ResampleOptions? options = null, bool pooled = false)
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
+ options ??= ResampleOptions.Default;
+ var target = pooled ? RgbaImage.Rent(width, height) : new RgbaImage(width, height);
+ try
+ {
+ if (width == source.Width && height == source.Height)
+ {
+ source.Pixels.CopyTo(target.Pixels);
+ return target;
+ }
+
+ Run(source, target, options);
+ return target;
+ }
+ catch
+ {
+ target.Dispose();
+ throw;
+ }
+ }
+
+ ///
+ /// The size that fits × inside a square of
+ /// , keeping the proportions (rounded, at least 1); the same size when it already fits.
+ ///
+ public static (int Width, int Height) FitWithin(int width, int height, int longSide)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(longSide);
+ var scale = Math.Min(1.0, (double)longSide / Math.Max(width, height));
+ return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
+ }
+
+ private static void Run(RgbaImage source, RgbaImage target, ResampleOptions options)
+ {
+ var premultiply = !source.IsOpaque();
+ var linear = options.LinearLight;
+ var horizontal = Weights.Build(source.Width, target.Width, options.Filter);
+ var vertical = Weights.Build(source.Height, target.Height, options.Filter);
+
+ var sw = source.Width;
+ var dw = target.Width;
+ var capacity = Math.Min(vertical.MaxTaps + 1, source.Height);
+ var pool = ArrayPool.Shared;
+ var input = pool.Rent(sw);
+ var accumulator = pool.Rent(dw);
+ var ring = new Vector4[capacity][];
+ var ringRow = new int[capacity];
+ try
+ {
+ for (var i = 0; i < capacity; i++)
+ {
+ ring[i] = pool.Rent(dw);
+ ringRow[i] = -1;
+ }
+
+ var toFloat = linear ? Tables.SrgbToLinear : Tables.Identity;
+ for (var y = 0; y < target.Height; y++)
+ {
+ var start = vertical.Start[y];
+ var count = vertical.Count[y];
+ var acc = accumulator.AsSpan(0, dw);
+ acc.Clear();
+ for (var k = 0; k < count; k++)
+ {
+ var sy = start + k;
+ var slot = sy % capacity;
+ if (ringRow[slot] != sy)
+ {
+ LoadRow(source.GetRow(sy), input.AsSpan(0, sw), toFloat, premultiply);
+ FilterRow(input.AsSpan(0, sw), ring[slot].AsSpan(0, dw), horizontal);
+ ringRow[slot] = sy;
+ }
+
+ var weight = vertical.Values[(y * vertical.MaxTaps) + k];
+ if (weight != 0)
+ {
+ AddScaled(acc, ring[slot].AsSpan(0, dw), weight);
+ }
+ }
+
+ StoreRow(acc, target.GetRow(y), linear, premultiply);
+ }
+ }
+ finally
+ {
+ pool.Return(input);
+ pool.Return(accumulator);
+ foreach (var row in ring)
+ {
+ if (row is not null)
+ {
+ pool.Return(row);
+ }
+ }
+ }
+ }
+
+ private static void LoadRow(ReadOnlySpan row, Span output, float[] toFloat, bool premultiply)
+ {
+ for (var x = 0; x < output.Length; x++)
+ {
+ var i = x * 4;
+ var a = row[i + 3] * (1f / 255f);
+ var value = new Vector4(toFloat[row[i]], toFloat[row[i + 1]], toFloat[row[i + 2]], a);
+ if (premultiply)
+ {
+ value = new Vector4(value.X * a, value.Y * a, value.Z * a, a);
+ }
+
+ output[x] = value;
+ }
+ }
+
+ private static void FilterRow(ReadOnlySpan input, Span output, Weights weights)
+ {
+ var taps = weights.MaxTaps;
+ var values = weights.Values;
+ for (var x = 0; x < output.Length; x++)
+ {
+ var start = weights.Start[x];
+ var count = weights.Count[x];
+ var w = values.AsSpan(x * taps, count);
+ var src = input.Slice(start, count);
+ var sum = Vector4.Zero;
+ for (var k = 0; k < w.Length; k++)
+ {
+ sum += src[k] * w[k];
+ }
+
+ output[x] = sum;
+ }
+ }
+
+ private static void AddScaled(Span accumulator, ReadOnlySpan row, float weight)
+ {
+ var acc = MemoryMarshal.Cast(accumulator);
+ var add = MemoryMarshal.Cast(row);
+ var i = 0;
+ if (Vector.IsHardwareAccelerated && acc.Length >= Vector.Count)
+ {
+ var w = new Vector(weight);
+ var accVectors = MemoryMarshal.Cast>(acc);
+ var addVectors = MemoryMarshal.Cast>(add);
+ for (var v = 0; v < accVectors.Length; v++)
+ {
+ accVectors[v] += addVectors[v] * w;
+ }
+
+ i = accVectors.Length * Vector.Count;
+ }
+
+ for (; i < acc.Length; i++)
+ {
+ acc[i] += add[i] * weight;
+ }
+ }
+
+ private static void StoreRow(ReadOnlySpan row, Span output, bool linear, bool premultiplied)
+ {
+ for (var x = 0; x < row.Length; x++)
+ {
+ var v = row[x];
+ var a = Math.Clamp(v.W, 0f, 1f);
+ var o = x * 4;
+ if (premultiplied)
+ {
+ if (v.W <= 0f)
+ {
+ output[o] = 0;
+ output[o + 1] = 0;
+ output[o + 2] = 0;
+ output[o + 3] = 0;
+ continue;
+ }
+
+ // Divided by the alpha as filtered, before clamping: the ratio of colour to alpha is what was averaged,
+ // and Lanczos overshooting at a hard edge must not tint the colour.
+ var inverse = 1f / v.W;
+ v = new Vector4(v.X * inverse, v.Y * inverse, v.Z * inverse, a);
+ }
+
+ output[o] = ToByte(v.X, linear);
+ output[o + 1] = ToByte(v.Y, linear);
+ output[o + 2] = ToByte(v.Z, linear);
+ output[o + 3] = (byte)((a * 255f) + 0.5f);
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static byte ToByte(float value, bool linear)
+ {
+ if (linear)
+ {
+ var index = (int)((value * (Tables.LinearSteps - 1)) + 0.5f);
+ return Tables.LinearToSrgb[Math.Clamp(index, 0, Tables.LinearSteps - 1)];
+ }
+
+ var v = (int)(value + 0.5f);
+ return (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
+ }
+
+ ///
+ /// The weights of one direction: for each target index the first source index, how many follow and their
+ /// weights (summing to 1), slots per target index. Source indices outside the image are
+ /// folded onto the nearest edge pixel.
+ ///
+ private sealed class Weights
+ {
+ private Weights(int[] start, int[] count, float[] values, int maxTaps)
+ {
+ Start = start;
+ Count = count;
+ Values = values;
+ MaxTaps = maxTaps;
+ }
+
+ public int[] Start { get; }
+
+ public int[] Count { get; }
+
+ public float[] Values { get; }
+
+ public int MaxTaps { get; }
+
+ public static Weights Build(int sourceLength, int targetLength, ResampleFilter filter)
+ {
+ var scale = (double)sourceLength / targetLength;
+ var stretch = Math.Max(1.0, scale);
+ var area = filter == ResampleFilter.Area;
+ double radius = area ? (scale > 1 ? 0.5 * scale : 1.0) : 3.0 * stretch;
+ var maxTaps = Math.Min(sourceLength, (int)Math.Ceiling(2 * radius) + 2);
+ var start = new int[targetLength];
+ var count = new int[targetLength];
+ var values = new float[targetLength * maxTaps];
+ Span raw = maxTaps <= 1024 ? stackalloc double[maxTaps] : new double[maxTaps];
+ for (var t = 0; t < targetLength; t++)
+ {
+ var centre = ((t + 0.5) * scale) - 0.5;
+ var first = (int)Math.Floor(centre - radius) + 1;
+ var last = (int)Math.Ceiling(centre + radius) - 1;
+ if (area && scale > 1)
+ {
+ // Exact coverage of [t·scale, (t+1)·scale) by the source cells.
+ var from = t * scale;
+ var to = from + scale;
+ first = (int)Math.Floor(from);
+ last = Math.Min(sourceLength - 1, (int)Math.Ceiling(to) - 1);
+ }
+
+ var lo = Math.Max(first, 0);
+ var hi = Math.Min(last, sourceLength - 1);
+ if (hi < lo)
+ {
+ lo = hi = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
+ }
+
+ var n = hi - lo + 1;
+ if (n > maxTaps)
+ {
+ // Only at the far edges of a very small source; keep the taps nearest the centre.
+ var middle = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
+ lo = Math.Clamp(middle - (maxTaps / 2), 0, sourceLength - maxTaps);
+ hi = lo + maxTaps - 1;
+ n = maxTaps;
+ }
+
+ raw[..n].Clear();
+ double sum = 0;
+ for (var s = first; s <= last; s++)
+ {
+ double weight;
+ if (area && scale > 1)
+ {
+ var from = t * scale;
+ weight = Math.Min(from + scale, s + 1) - Math.Max(from, s);
+ }
+ else if (area)
+ {
+ weight = Math.Max(0, 1 - Math.Abs(s - centre));
+ }
+ else
+ {
+ weight = Lanczos3((s - centre) / stretch);
+ }
+
+ if (weight == 0)
+ {
+ continue;
+ }
+
+ var index = Math.Clamp(s, lo, hi) - lo;
+ raw[index] += weight;
+ sum += weight;
+ }
+
+ if (sum == 0)
+ {
+ raw[Math.Clamp((int)Math.Round(centre), lo, hi) - lo] = 1;
+ sum = 1;
+ }
+
+ start[t] = lo;
+ count[t] = n;
+ var row = values.AsSpan(t * maxTaps, maxTaps);
+ for (var i = 0; i < n; i++)
+ {
+ row[i] = (float)(raw[i] / sum);
+ }
+ }
+
+ return new Weights(start, count, values, maxTaps);
+ }
+
+ private static double Lanczos3(double x)
+ {
+ x = Math.Abs(x);
+ if (x < 1e-9)
+ {
+ return 1;
+ }
+
+ if (x >= 3)
+ {
+ return 0;
+ }
+
+ var px = Math.PI * x;
+ return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
+ }
+ }
+
+ /// Conversions between 8-bit sRGB and linear light (IEC 61966-2-1).
+ internal static class Tables
+ {
+ public const int LinearSteps = 4096;
+
+ public static readonly float[] Identity = BuildIdentity();
+
+ public static readonly float[] SrgbToLinear = BuildToLinear();
+
+ public static readonly byte[] LinearToSrgb = BuildToSrgb();
+
+ private static float[] BuildIdentity()
+ {
+ var table = new float[256];
+ for (var i = 0; i < table.Length; i++)
+ {
+ table[i] = i;
+ }
+
+ return table;
+ }
+
+ private static float[] BuildToLinear()
+ {
+ var table = new float[256];
+ for (var i = 0; i < table.Length; i++)
+ {
+ var c = i / 255.0;
+ table[i] = (float)(c <= 0.04045 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4));
+ }
+
+ return table;
+ }
+
+ private static byte[] BuildToSrgb()
+ {
+ var table = new byte[LinearSteps];
+ for (var i = 0; i < table.Length; i++)
+ {
+ var l = i / (double)(LinearSteps - 1);
+ var c = l <= 0.0031308 ? l * 12.92 : (1.055 * Math.Pow(l, 1 / 2.4)) - 0.055;
+ table[i] = (byte)Math.Clamp((int)Math.Round(c * 255), 0, 255);
+ }
+
+ return table;
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/JpegDct.cs b/src/Febe.Core/Codecs/Images/JpegDct.cs
index 05463a8..8e670e2 100644
--- a/src/Febe.Core/Codecs/Images/JpegDct.cs
+++ b/src/Febe.Core/Codecs/Images/JpegDct.cs
@@ -73,6 +73,50 @@ internal static class JpegDct
}
}
+ ///
+ /// Like , but writes the block reduced by 2^ (1 to 3) in each
+ /// direction: every output sample is the rounded mean of a square of the full block's samples. At an eighth that
+ /// mean is the DC term alone (S00 / 8 plus the level shift: the AC basis functions sum to zero over the block), so
+ /// no transform is computed.
+ ///
+ public static void InverseReduced(ReadOnlySpan block, ReadOnlySpan quantization, Span output, int stride, int precision, ReadOnlySpan to8Bit, int shift)
+ {
+ var max = precision == 12 ? 4095 : 255;
+ if (shift >= 3)
+ {
+ var level = precision == 12 ? 2048 : 128;
+ var value = (int)Math.Floor((block[0] * quantization[0] / 8.0) + level + 0.5);
+ value = Math.Clamp(value, 0, max);
+ output[0] = precision == 12 ? to8Bit[value] : (byte)value;
+ return;
+ }
+
+ Span full = stackalloc byte[64];
+ Inverse(block, quantization, full, 8, precision, to8Bit);
+ var n = 8 >> shift;
+ var side = 1 << shift;
+ var area = side * side;
+ var half = area >> 1;
+ for (var y = 0; y < n; y++)
+ {
+ var o = output.Slice(y * stride, n);
+ for (var x = 0; x < n; x++)
+ {
+ var sum = 0;
+ for (var dy = 0; dy < side; dy++)
+ {
+ var row = full.Slice((((y * side) + dy) * 8) + (x * side), side);
+ for (var dx = 0; dx < side; dx++)
+ {
+ sum += row[dx];
+ }
+ }
+
+ o[x] = (byte)((sum + half) / area);
+ }
+ }
+ }
+
///
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
/// not yet quantized.
diff --git a/src/Febe.Core/Codecs/Images/JpegDecoder.cs b/src/Febe.Core/Codecs/Images/JpegDecoder.cs
index 8ada0d5..31109a9 100644
--- a/src/Febe.Core/Codecs/Images/JpegDecoder.cs
+++ b/src/Febe.Core/Codecs/Images/JpegDecoder.cs
@@ -49,6 +49,23 @@ public static class JpegDecoder
return image;
}
+ ///
+ /// Decodes a JPEG reduced by 2^ in each direction (0 full size, 1 half, 2 quarter,
+ /// 3 eighth; sizes rounded up), with what returns (the full size): each 8×8 block gives the
+ /// means of its squares of samples, which saves memory and, at an eighth, the whole inverse transform. Lossless
+ /// files are always decoded at full size: check the size of the result.
+ ///
+ public static RgbaImage DecodeReduced(ReadOnlyMemory data, int reduction, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(reduction);
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(reduction, 3);
+ using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true) { ScaleShift = reduction };
+ file.Run();
+ var image = file.Render(pooled);
+ info = file.ToInfo();
+ return image;
+ }
+
///
/// The quantized DCT coefficients of every block of a DCT-based JPEG, as they stand after the last scan, with the
/// frame parameters: what tests compare between encodings of the same image (sequential, progressive, restart).
diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs
index a2dd77f..96a7934 100644
--- a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs
+++ b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs
@@ -66,7 +66,7 @@ internal sealed partial class JpegFile
DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], 1, 63, 0, block, zigzag);
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
{
- JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
+ TransformBlock(c, plane, block, bx, by, to8);
}
break;
diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs
index 263a240..dfacbb1 100644
--- a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs
+++ b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs
@@ -92,7 +92,7 @@ internal sealed partial class JpegFile
DecodeSequential(ref reader, dcTables[ci]!, acTables[ci]!, ref c.DcPredictor, block, zigzag);
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
{
- JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
+ TransformBlock(c, plane, block, bx, by, to8);
}
break;
diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Render.cs b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs
index ff30494..18a5a7e 100644
--- a/src/Febe.Core/Codecs/Images/JpegFile.Render.cs
+++ b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs
@@ -46,17 +46,19 @@ internal sealed partial class JpegFile
public RgbaImage Render(bool pooled)
{
- var image = RgbaImage.Create(Width, Height, _limits, pooled);
+ var width = OutputWidth;
+ var height = OutputHeight;
+ var image = RgbaImage.Create(width, height, _limits, pooled);
var buffers = new byte[Components.Length][];
try
{
for (var i = 0; i < buffers.Length; i++)
{
- buffers[i] = ArrayPool.Shared.Rent(Width + 1);
+ buffers[i] = ArrayPool.Shared.Rent(width + 1);
}
var model = Colors;
- for (var y = 0; y < Height; y++)
+ for (var y = 0; y < height; y++)
{
var output = image.GetRow(y);
var c0 = UpsampleRow(Components[0], y, buffers[0]);
@@ -103,7 +105,7 @@ internal sealed partial class JpegFile
}
///
- /// Row of the image for component , samples. A ratio
+ /// Row of the image for component , samples. A ratio
/// of 2 to the largest sampling factor uses the triangular ("fancy") filter of the JFIF siting: each output sample
/// weighs 3/4 the nearest input sample and 1/4 the next one, the edges repeating; other ratios repeat samples.
///
@@ -111,22 +113,23 @@ internal sealed partial class JpegFile
{
var plane = c.Plane!;
var stride = c.PlaneStride;
- var width = Width;
+ var width = OutputWidth;
if (c.H == MaxH && c.V == MaxV)
{
return plane.AsSpan(y * stride, width);
}
var output = buffer.AsSpan(0, width);
- var lastX = c.Width - 1;
- var lastY = c.Height - 1;
+ var componentWidth = Reduce(c.Width);
+ var lastX = componentWidth - 1;
+ var lastY = Reduce(c.Height) - 1;
var integral = MaxH % c.H == 0 && MaxV % c.V == 0;
var hr = MaxH / c.H;
var vr = MaxV / c.V;
if (!integral || hr > 2 || vr > 2)
{
var sy = Math.Min((int)((long)y * c.V / MaxV), lastY);
- var row = plane.AsSpan(sy * stride, c.Width);
+ var row = plane.AsSpan(sy * stride, componentWidth);
for (var x = 0; x < width; x++)
{
output[x] = row[Math.Min((int)((long)x * c.H / MaxH), lastX)];
@@ -138,7 +141,7 @@ internal sealed partial class JpegFile
if (vr == 1)
{
// hr == 2.
- var row = plane.AsSpan(y * stride, c.Width);
+ var row = plane.AsSpan(y * stride, componentWidth);
for (var i = 0; i <= lastX; i++)
{
var three = row[i] * 3;
@@ -155,8 +158,8 @@ internal sealed partial class JpegFile
var cy = y >> 1;
var farY = (y & 1) == 0 ? Math.Max(cy - 1, 0) : Math.Min(cy + 1, lastY);
- var near = plane.AsSpan(cy * stride, c.Width);
- var far = plane.AsSpan(farY * stride, c.Width);
+ var near = plane.AsSpan(cy * stride, componentWidth);
+ var far = plane.AsSpan(farY * stride, componentWidth);
if (hr == 1)
{
var bias = (y & 1) == 0 ? 1 : 2;
diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs
index 1323744..1d5f73e 100644
--- a/src/Febe.Core/Codecs/Images/JpegFile.cs
+++ b/src/Febe.Core/Codecs/Images/JpegFile.cs
@@ -79,6 +79,7 @@ internal sealed partial class JpegFile : IDisposable
private bool _allocated;
private bool _pooledArrays;
+ private int _scaleShift;
private int _scanCount;
private int _sosEnd;
@@ -119,6 +120,25 @@ internal sealed partial class JpegFile : IDisposable
public JpegComponent[] Components { get; private set; } = [];
+ ///
+ /// The reduction of a DCT image decoded to samples, as a power of two (0 full size, 1 half, 2 quarter, 3 eighth):
+ /// each 8×8 block gives (8 >> shift)² samples, the means of its squares of samples (only its DC term at an
+ /// eighth). Set before ; a lossless file is always decoded at full size.
+ ///
+ public int ScaleShift
+ {
+ get => _scaleShift;
+ set => _scaleShift = Math.Clamp(value, 0, 3);
+ }
+
+ /// Width of the decoded image: reduced by , rounded up.
+ public int OutputWidth => Reduce(Width);
+
+ /// Height of the decoded image: reduced by , rounded up.
+ public int OutputHeight => Reduce(Height);
+
+ private int Reduce(int length) => (length + (1 << _scaleShift) - 1) >> _scaleShift;
+
public int MaxH { get; private set; }
public int MaxV { get; private set; }
@@ -767,14 +787,19 @@ internal sealed partial class JpegFile : IDisposable
private void Allocate()
{
- _limits.CheckSize(Width, Height);
+ if (Lossless || _mode != Mode.Pixels)
+ {
+ _scaleShift = 0;
+ }
+
+ _limits.CheckSize(OutputWidth, OutputHeight);
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
long bytes = 0;
foreach (var c in Components)
{
var unit = Lossless ? 1 : 8;
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
- bytes += samples;
+ bytes += samples >> (2 * _scaleShift);
if (keepCoefficients && !Lossless)
{
bytes += samples * 2;
@@ -792,11 +817,12 @@ internal sealed partial class JpegFile : IDisposable
foreach (var c in Components)
{
var unit = Lossless ? 1 : 8;
- c.PlaneStride = c.PaddedUnitsWide * unit;
+ var planeUnit = unit >> _scaleShift;
+ c.PlaneStride = c.PaddedUnitsWide * planeUnit;
var samples = c.PlaneStride * c.PaddedUnitsHigh * unit;
if (_mode == Mode.Pixels)
{
- c.Plane = ArrayPool.Shared.Rent(samples);
+ c.Plane = ArrayPool.Shared.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit);
}
if (Lossless)
@@ -984,11 +1010,26 @@ internal sealed partial class JpegFile : IDisposable
for (var bx = 0; bx < c.UnitsWide; bx++)
{
var block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64);
- JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
+ TransformBlock(c, plane, block, bx, by, to8);
}
}
}
+ /// The samples of one block into the plane of its component, at the scale of .
+ private void TransformBlock(JpegComponent c, byte[] plane, ReadOnlySpan block, int bx, int by, ReadOnlySpan to8)
+ {
+ var n = 8 >> _scaleShift;
+ var output = plane.AsSpan((by * n * c.PlaneStride) + (bx * n));
+ if (_scaleShift == 0)
+ {
+ JpegDct.Inverse(block, c.Quantization, output, c.PlaneStride, Precision, to8);
+ }
+ else
+ {
+ JpegDct.InverseReduced(block, c.Quantization, output, c.PlaneStride, Precision, to8, _scaleShift);
+ }
+ }
+
/// 12-bit samples to 8 bits, rounded.
private static class Twelve
{
diff --git a/src/Febe.Core/Codecs/Images/PngEncoder.cs b/src/Febe.Core/Codecs/Images/PngEncoder.cs
index 431056d..4f98482 100644
--- a/src/Febe.Core/Codecs/Images/PngEncoder.cs
+++ b/src/Febe.Core/Codecs/Images/PngEncoder.cs
@@ -59,6 +59,12 @@ public sealed record PngEncoderOptions
/// XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».
public string? Xmp { get; init; }
+
+ ///
+ /// Texts to write, in order, after the pixels: a tEXt chunk when keyword and text are Latin-1 and there is no
+ /// language, an uncompressed iTXt chunk otherwise. Keywords: 1 to 79 printable Latin-1 characters.
+ ///
+ public IReadOnlyList Texts { get; init; } = [];
}
///
@@ -85,6 +91,13 @@ public static class PngEncoder
options ??= PngEncoderOptions.Default;
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
var iccName = options.IccProfile is null ? null : IccName(options.IccProfileName);
+ foreach (var text in options.Texts)
+ {
+ if (!IsValidKeyword(text.Keyword))
+ {
+ throw new ArgumentException($"«{text.Keyword}» is not a valid PNG keyword.", nameof(options));
+ }
+ }
var alpha = options.ColorMode switch
{
@@ -143,6 +156,11 @@ public static class PngEncoder
idat.Complete();
}
+ foreach (var text in options.Texts)
+ {
+ WriteText(output, text);
+ }
+
WriteChunk(output, "IEND"u8, []);
}
@@ -295,6 +313,61 @@ public static class PngEncoder
return span.ToArray();
}
+ /// Whether can name a PNG text chunk: 1-79 printable Latin-1, no outer or double spaces.
+ public static bool IsValidKeyword(string keyword)
+ {
+ if (string.IsNullOrEmpty(keyword) || keyword.Length > 79 || keyword[0] == ' ' || keyword[^1] == ' ' || keyword.Contains(" ", StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ foreach (var c in keyword)
+ {
+ if (c is < ' ' or (> '~' and < '¡') or > 'ÿ')
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static void WriteText(Stream output, ImageText text)
+ {
+ using var payload = new MemoryStream();
+ payload.Write(Encoding.Latin1.GetBytes(text.Keyword));
+ payload.WriteByte(0);
+ var latin1 = text.Language.Length == 0 && text.TranslatedKeyword.Length == 0 && IsLatin1(text.Text);
+ if (latin1)
+ {
+ payload.Write(Encoding.Latin1.GetBytes(text.Text));
+ WriteChunk(output, "tEXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
+ return;
+ }
+
+ payload.WriteByte(0); // not compressed
+ payload.WriteByte(0); // method
+ payload.Write(Encoding.ASCII.GetBytes(text.Language));
+ payload.WriteByte(0);
+ payload.Write(Encoding.UTF8.GetBytes(text.TranslatedKeyword));
+ payload.WriteByte(0);
+ payload.Write(Encoding.UTF8.GetBytes(text.Text));
+ WriteChunk(output, "iTXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
+ }
+
+ private static bool IsLatin1(string text)
+ {
+ foreach (var c in text)
+ {
+ if (c > '\u00FF' || c == '\0')
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
private static byte[] IccName(string name)
{
if (name.Length is < 1 or > 79 || name[0] == ' ' || name[^1] == ' ')
diff --git a/src/Febe.Core/Drawing/Brush.cs b/src/Febe.Core/Drawing/Brush.cs
new file mode 100644
index 0000000..5ee787f
--- /dev/null
+++ b/src/Febe.Core/Drawing/Brush.cs
@@ -0,0 +1,118 @@
+using System.Numerics;
+
+namespace Febe.Core.Drawing;
+
+/// What fills a shape: one colour or a gradient.
+public abstract class Brush
+{
+ private protected Brush()
+ {
+ }
+
+ ///
+ /// The colours of .Length pixels of row from column
+ /// : red, green and blue 0-255, alpha 0-1, not premultiplied. maps
+ /// canvas pixels back to the coordinates the brush was defined in.
+ ///
+ internal abstract void Shade(in Matrix3x2 toUser, int y, int x0, Span output);
+
+ /// A colour as the shading works with it.
+ internal static Vector4 ToVector(Color color) => new(color.R, color.G, color.B, color.A / 255f);
+}
+
+/// One colour.
+public sealed class SolidBrush(Color color) : Brush
+{
+ public Color Color { get; } = color;
+
+ internal Vector4 Value { get; } = ToVector(color);
+
+ internal override void Shade(in Matrix3x2 toUser, int y, int x0, Span output) => output.Fill(Value);
+}
+
+///
+/// A linear gradient from to : the colours change along that line and stay the
+/// same across it; before the start and after the end the first and last colours continue. Colours are interpolated
+/// without premultiplying.
+///
+public sealed class LinearGradientBrush : Brush
+{
+ private readonly Vector4[] _colors;
+ private readonly float[] _positions;
+
+ /// Where the first colour is, in the coordinates the shape is drawn in.
+ /// Where the last colour is.
+ /// Two or more colours.
+ /// Where each colour sits between start (0) and end (1), increasing; evenly spaced when null.
+ public LinearGradientBrush(Vector2 start, Vector2 end, IReadOnlyList colors, IReadOnlyList? positions = null)
+ {
+ ArgumentNullException.ThrowIfNull(colors);
+ if (colors.Count < 2)
+ {
+ throw new ArgumentException("A gradient needs at least two colours.", nameof(colors));
+ }
+
+ if (positions is not null && positions.Count != colors.Count)
+ {
+ throw new ArgumentException("One position per colour.", nameof(positions));
+ }
+
+ Start = start;
+ End = end;
+ _colors = new Vector4[colors.Count];
+ _positions = new float[colors.Count];
+ for (var i = 0; i < colors.Count; i++)
+ {
+ _colors[i] = ToVector(colors[i]);
+ _positions[i] = positions is null ? i / (float)(colors.Count - 1) : Math.Clamp(positions[i], i == 0 ? 0 : _positions[i - 1], 1);
+ }
+ }
+
+ public Vector2 Start { get; }
+
+ public Vector2 End { get; }
+
+ internal override void Shade(in Matrix3x2 toUser, int y, int x0, Span output)
+ {
+ var direction = End - Start;
+ var lengthSquared = direction.LengthSquared();
+ if (lengthSquared < 1e-12f)
+ {
+ output.Fill(_colors[^1]);
+ return;
+ }
+
+ // t = (p − start)·d / |d|², p the centre of the pixel in user coordinates; it grows by a constant per column.
+ var first = Vector2.Transform(new Vector2(x0 + 0.5f, y + 0.5f), toUser);
+ var t = Vector2.Dot(first - Start, direction) / lengthSquared;
+ var step = Vector2.Dot(new Vector2(toUser.M11, toUser.M12), direction) / lengthSquared;
+ for (var i = 0; i < output.Length; i++)
+ {
+ output[i] = At(t + (step * i));
+ }
+ }
+
+ private Vector4 At(float t)
+ {
+ if (t <= _positions[0])
+ {
+ return _colors[0];
+ }
+
+ var last = _positions.Length - 1;
+ if (t >= _positions[last])
+ {
+ return _colors[last];
+ }
+
+ var i = 1;
+ while (_positions[i] < t)
+ {
+ i++;
+ }
+
+ var span = _positions[i] - _positions[i - 1];
+ var f = span <= 0 ? 1 : (t - _positions[i - 1]) / span;
+ return Vector4.Lerp(_colors[i - 1], _colors[i], f);
+ }
+}
diff --git a/src/Febe.Core/Drawing/Canvas.cs b/src/Febe.Core/Drawing/Canvas.cs
new file mode 100644
index 0000000..b738d8e
--- /dev/null
+++ b/src/Febe.Core/Drawing/Canvas.cs
@@ -0,0 +1,549 @@
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using Febe.Core.Codecs.Images;
+
+namespace Febe.Core.Drawing;
+
+/// How the ends of a stroked line look.
+public enum LineCap
+{
+ /// The line stops at its end points.
+ Butt,
+
+ /// A half circle around each end point.
+ Round,
+
+ /// The line goes on for half its width beyond each end point.
+ Square,
+}
+
+///
+/// Draws anti-aliased shapes on an : filled paths, rectangles, circles and ellipses, stroked
+/// lines and outlines, linear gradients, blurred discs and resized images, each composited over what is there
+/// (source over, straight alpha). Coordinates go through , which ,
+/// and change and / keep.
+/// Written in house (no graphics library): the coverage of every pixel is the exact area of the shape inside it.
+///
+public sealed class Canvas : IDisposable
+{
+ private readonly RgbaImage _target;
+ private readonly Stack _saved = new();
+ private readonly CoverageRasterizer _rasterizer = new();
+
+ public Canvas(RgbaImage target)
+ {
+ ArgumentNullException.ThrowIfNull(target);
+ _target = target;
+ }
+
+ public int Width => _target.Width;
+
+ public int Height => _target.Height;
+
+ /// The image drawn on.
+ public RgbaImage Target => _target;
+
+ /// From the coordinates of the shapes to the pixels of the canvas.
+ public Matrix2D Transform { get; set; } = Matrix2D.Identity;
+
+ /// Remembers the transform, for .
+ public void Save() => _saved.Push(Transform);
+
+ /// Back to the transform of the last .
+ public void Restore() => Transform = _saved.Count > 0 ? _saved.Pop() : Matrix2D.Identity;
+
+ public void Translate(float x, float y) => Transform = Transform.Then(Matrix2D.Translation(x, y));
+
+ public void Scale(float x, float y) => Transform = Transform.Then(Matrix2D.Scaling(x, y));
+
+ public void Scale(float factor) => Scale(factor, factor);
+
+ /// Rotates the shapes drawn next by around the origin, clockwise on screen.
+ public void Rotate(float degrees) => Transform = Transform.Then(Matrix2D.Rotation(degrees));
+
+ /// Every pixel set to , ignoring what was there.
+ public void Clear(Color color)
+ {
+ var pixels = _target.Pixels;
+ Span one = [color.R, color.G, color.B, color.A];
+ for (var i = 0; i < pixels.Length; i += 4)
+ {
+ one.CopyTo(pixels.Slice(i, 4));
+ }
+ }
+
+ public void Fill(PathBuilder path, Color color) => Fill(path, new SolidBrush(color));
+
+ /// Fills the shape describes (non-zero winding).
+ public void Fill(PathBuilder path, Brush brush)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ ArgumentNullException.ThrowIfNull(brush);
+ var contours = path.Flatten(Transform);
+ FillPolygons(contours, brush);
+ }
+
+ public void FillRect(float x, float y, float width, float height, Color color) => FillRect(x, y, width, height, new SolidBrush(color));
+
+ /// Fills a rectangle; without rotation the coverage of its border pixels is computed directly.
+ public void FillRect(float x, float y, float width, float height, Brush brush)
+ {
+ ArgumentNullException.ThrowIfNull(brush);
+ var m = Transform.Value;
+ if (m.M12 == 0 && m.M21 == 0)
+ {
+ var a = Transform.Apply(new Vector2(x, y));
+ var b = Transform.Apply(new Vector2(x + width, y + height));
+ FillAlignedRect(MathF.Min(a.X, b.X), MathF.Min(a.Y, b.Y), MathF.Max(a.X, b.X), MathF.Max(a.Y, b.Y), brush);
+ return;
+ }
+
+ Fill(new PathBuilder().AddRect(x, y, width, height), brush);
+ }
+
+ public void FillRoundRect(float x, float y, float width, float height, float radius, Color color) =>
+ Fill(new PathBuilder().AddRoundRect(x, y, width, height, radius), color);
+
+ public void FillCircle(float cx, float cy, float r, Color color) => Fill(new PathBuilder().AddCircle(cx, cy, r), color);
+
+ public void FillEllipse(float cx, float cy, float rx, float ry, Color color) => Fill(new PathBuilder().AddEllipse(cx, cy, rx, ry), color);
+
+ /// The outline of a rectangle, wide and centred on its sides, square corners.
+ public void StrokeRect(float x, float y, float width, float height, float lineWidth, Color color)
+ {
+ var half = lineWidth / 2;
+ var path = new PathBuilder().AddRect(x - half, y - half, width + lineWidth, height + lineWidth);
+ if (width > lineWidth && height > lineWidth)
+ {
+ path.AddRect(x + half, y + half, width - lineWidth, height - lineWidth, clockwise: false);
+ }
+
+ Fill(path, color);
+ }
+
+ /// A ring: the outline of an ellipse, wide and centred on it.
+ public void StrokeEllipse(float cx, float cy, float rx, float ry, float lineWidth, Color color)
+ {
+ var half = lineWidth / 2;
+ var path = new PathBuilder().AddEllipse(cx, cy, rx + half, ry + half);
+ if (rx > half && ry > half)
+ {
+ path.AddEllipse(cx, cy, rx - half, ry - half, clockwise: false);
+ }
+
+ Fill(path, color);
+ }
+
+ public void StrokeCircle(float cx, float cy, float r, float lineWidth, Color color) => StrokeEllipse(cx, cy, r, r, lineWidth, color);
+
+ /// A straight line wide.
+ public void DrawLine(float x0, float y0, float x1, float y1, float lineWidth, Color color, LineCap cap = LineCap.Butt) =>
+ Stroke(new PathBuilder().MoveTo(x0, y0).LineTo(x1, y1), lineWidth, color, cap);
+
+ ///
+ /// The contours of drawn as lines wide, with round joins
+ /// and the given caps on open contours.
+ ///
+ public void Stroke(PathBuilder path, float lineWidth, Color color, LineCap cap = LineCap.Butt)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ if (lineWidth <= 0)
+ {
+ return;
+ }
+
+ var half = lineWidth * Transform.LengthScale / 2;
+ var pieces = new List();
+ foreach (var contour in path.Flatten(Transform))
+ {
+ StrokePieces(contour, half, cap, pieces);
+ }
+
+ FillPolygons(pieces, new SolidBrush(color));
+ }
+
+ ///
+ /// A disc whose edge is blurred by a Gaussian of (in the units of the shapes): the
+ /// coverage at distance d from the centre is ½·erfc((d − r) / (σ√2)), the disc convolved with the Gaussian
+ /// across its edge.
+ ///
+ public void FillBlurredCircle(float cx, float cy, float r, float sigma, Color color)
+ {
+ var scale = Transform.LengthScale;
+ var centre = Transform.Apply(new Vector2(cx, cy));
+ var radius = r * scale;
+ var s = MathF.Max(sigma * scale, 1e-3f);
+ var reach = radius + (3.5f * s);
+ var left = Math.Max(0, (int)MathF.Floor(centre.X - reach));
+ var right = Math.Min(Width, (int)MathF.Ceiling(centre.X + reach));
+ var top = Math.Max(0, (int)MathF.Floor(centre.Y - reach));
+ var bottom = Math.Min(Height, (int)MathF.Ceiling(centre.Y + reach));
+ if (left >= right || top >= bottom)
+ {
+ return;
+ }
+
+ var rgba = Brush.ToVector(color);
+ var inverse = 1 / (s * MathF.Sqrt(2));
+ for (var y = top; y < bottom; y++)
+ {
+ var row = _target.GetRow(y);
+ var dy = y + 0.5f - centre.Y;
+ for (var x = left; x < right; x++)
+ {
+ var dx = x + 0.5f - centre.X;
+ var d = MathF.Sqrt((dx * dx) + (dy * dy));
+ var coverage = 0.5f * Erfc((d - radius) * inverse);
+ if (coverage > 1f / 1024)
+ {
+ BlendPixel(row.Slice(x * 4, 4), rgba, rgba.W * coverage);
+ }
+ }
+ }
+ }
+
+ /// Composites one colour over one pixel, without anti-aliasing (canvas pixels, the transform ignored).
+ public void BlendPixel(int x, int y, Color color)
+ {
+ if ((uint)x >= (uint)Width || (uint)y >= (uint)Height)
+ {
+ return;
+ }
+
+ var rgba = Brush.ToVector(color);
+ BlendPixel(_target.GetRow(y).Slice(x * 4, 4), rgba, rgba.W);
+ }
+
+ ///
+ /// Draws resized (Lanczos) to the rectangle (x, y, width, height) in canvas pixels, its
+ /// edges rounded to whole pixels, over what is there; the transform is not applied.
+ ///
+ public void DrawImage(RgbaImage image, float x, float y, float width, float height)
+ {
+ ArgumentNullException.ThrowIfNull(image);
+ var left = (int)MathF.Round(x);
+ var top = (int)MathF.Round(y);
+ var w = (int)MathF.Round(x + width) - left;
+ var h = (int)MathF.Round(y + height) - top;
+ if (w <= 0 || h <= 0)
+ {
+ return;
+ }
+
+ using var resized = ImageResampler.Resize(image, w, h, pooled: true);
+ for (var row = 0; row < h; row++)
+ {
+ var ty = top + row;
+ if ((uint)ty >= (uint)Height)
+ {
+ continue;
+ }
+
+ var source = resized.GetRow(row);
+ var target = _target.GetRow(ty);
+ for (var col = 0; col < w; col++)
+ {
+ var tx = left + col;
+ if ((uint)tx >= (uint)Width)
+ {
+ continue;
+ }
+
+ var s = source.Slice(col * 4, 4);
+ if (s[3] == 0)
+ {
+ continue;
+ }
+
+ BlendPixel(target.Slice(tx * 4, 4), new Vector4(s[0], s[1], s[2], s[3] / 255f), s[3] / 255f);
+ }
+ }
+ }
+
+ public void Dispose() => _rasterizer.Dispose();
+
+ private void FillPolygons(IReadOnlyList contours, Brush brush)
+ {
+ var polygons = new List(contours.Count);
+ foreach (var contour in contours)
+ {
+ if (contour.Points.Length >= 3)
+ {
+ polygons.Add(contour.Points);
+ }
+ }
+
+ FillPolygons(polygons, brush);
+ }
+
+ private void FillPolygons(List polygons, Brush brush)
+ {
+ if (polygons.Count == 0)
+ {
+ return;
+ }
+
+ var minX = float.MaxValue;
+ var minY = float.MaxValue;
+ var maxX = float.MinValue;
+ var maxY = float.MinValue;
+ foreach (var polygon in polygons)
+ {
+ foreach (var p in polygon)
+ {
+ minX = MathF.Min(minX, p.X);
+ minY = MathF.Min(minY, p.Y);
+ maxX = MathF.Max(maxX, p.X);
+ maxY = MathF.Max(maxY, p.Y);
+ }
+ }
+
+ if (!float.IsFinite(minX) || !float.IsFinite(maxX) || !float.IsFinite(minY) || !float.IsFinite(maxY))
+ {
+ return;
+ }
+
+ var left = Math.Max(0, (int)MathF.Floor(minX));
+ var top = Math.Max(0, (int)MathF.Floor(minY));
+ var right = Math.Min(Width, (int)MathF.Ceiling(maxX) + 1);
+ var bottom = Math.Min(Height, (int)MathF.Ceiling(maxY) + 1);
+ if (left >= right || top >= bottom)
+ {
+ return;
+ }
+
+ _rasterizer.Reset(left, top, right - left, bottom - top);
+ foreach (var polygon in polygons)
+ {
+ _rasterizer.AddPolygon(polygon);
+ }
+
+ var width = right - left;
+ var coverage = ArrayPool.Shared.Rent(width);
+ try
+ {
+ for (var y = 0; y < bottom - top; y++)
+ {
+ _rasterizer.Coverage(y, coverage.AsSpan(0, width));
+ BlendRow(top + y, left, coverage.AsSpan(0, width), brush);
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(coverage);
+ }
+ }
+
+ private void FillAlignedRect(float x0, float y0, float x1, float y1, Brush brush)
+ {
+ var left = Math.Max(0, (int)MathF.Floor(x0));
+ var right = Math.Min(Width, (int)MathF.Ceiling(x1));
+ var top = Math.Max(0, (int)MathF.Floor(y0));
+ var bottom = Math.Min(Height, (int)MathF.Ceiling(y1));
+ if (left >= right || top >= bottom)
+ {
+ return;
+ }
+
+ var width = right - left;
+ var columns = ArrayPool.Shared.Rent(width);
+ var coverage = ArrayPool.Shared.Rent(width);
+ try
+ {
+ for (var i = 0; i < width; i++)
+ {
+ var px = left + i;
+ columns[i] = MathF.Max(0, MathF.Min(px + 1, x1) - MathF.Max(px, x0));
+ }
+
+ for (var y = top; y < bottom; y++)
+ {
+ var rowCoverage = MathF.Max(0, MathF.Min(y + 1, y1) - MathF.Max(y, y0));
+ for (var i = 0; i < width; i++)
+ {
+ coverage[i] = columns[i] * rowCoverage;
+ }
+
+ BlendRow(y, left, coverage.AsSpan(0, width), brush);
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(columns);
+ ArrayPool.Shared.Return(coverage);
+ }
+ }
+
+ private void BlendRow(int y, int left, ReadOnlySpan coverage, Brush brush)
+ {
+ var row = _target.GetRow(y);
+ if (brush is SolidBrush solid)
+ {
+ var color = solid.Value;
+ for (var i = 0; i < coverage.Length; i++)
+ {
+ var c = coverage[i];
+ if (c > 1f / 1024)
+ {
+ BlendPixel(row.Slice((left + i) * 4, 4), color, color.W * c);
+ }
+ }
+
+ return;
+ }
+
+ Matrix3x2.Invert(Transform.Value, out var toUser);
+ var colors = ArrayPool.Shared.Rent(coverage.Length);
+ try
+ {
+ var shades = colors.AsSpan(0, coverage.Length);
+ brush.Shade(toUser, y, left, shades);
+ for (var i = 0; i < coverage.Length; i++)
+ {
+ var c = coverage[i];
+ if (c > 1f / 1024)
+ {
+ BlendPixel(row.Slice((left + i) * 4, 4), shades[i], shades[i].W * c);
+ }
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(colors);
+ }
+ }
+
+ /// Source over, straight alpha: is the colour's alpha times the coverage.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static void BlendPixel(Span pixel, Vector4 color, float alpha)
+ {
+ if (alpha <= 0)
+ {
+ return;
+ }
+
+ if (alpha >= 1)
+ {
+ pixel[0] = (byte)(color.X + 0.5f);
+ pixel[1] = (byte)(color.Y + 0.5f);
+ pixel[2] = (byte)(color.Z + 0.5f);
+ pixel[3] = 255;
+ return;
+ }
+
+ int below = pixel[3];
+ if (below == 255)
+ {
+ pixel[0] = (byte)(pixel[0] + ((color.X - pixel[0]) * alpha) + 0.5f);
+ pixel[1] = (byte)(pixel[1] + ((color.Y - pixel[1]) * alpha) + 0.5f);
+ pixel[2] = (byte)(pixel[2] + ((color.Z - pixel[2]) * alpha) + 0.5f);
+ return;
+ }
+
+ var da = below / 255f;
+ var outAlpha = alpha + (da * (1 - alpha));
+ var keep = da * (1 - alpha) / outAlpha;
+ var take = alpha / outAlpha;
+ pixel[0] = (byte)((color.X * take) + (pixel[0] * keep) + 0.5f);
+ pixel[1] = (byte)((color.Y * take) + (pixel[1] * keep) + 0.5f);
+ pixel[2] = (byte)((color.Z * take) + (pixel[2] * keep) + 0.5f);
+ pixel[3] = (byte)((outAlpha * 255) + 0.5f);
+ }
+
+ /// The pieces of a stroke: a quadrilateral per segment, a disc per join, the caps; all turning the same way.
+ private static void StrokePieces(Polyline contour, float half, LineCap cap, List pieces)
+ {
+ var points = contour.Points;
+ var count = points.Length;
+ if (count < 2)
+ {
+ return;
+ }
+
+ var segments = contour.Closed ? count : count - 1;
+ for (var i = 0; i < segments; i++)
+ {
+ var a = points[i];
+ var b = points[(i + 1) % count];
+ var along = b - a;
+ var length = along.Length();
+ if (length < 1e-6f)
+ {
+ continue;
+ }
+
+ var unit = along / length;
+ if (!contour.Closed && cap == LineCap.Square)
+ {
+ if (i == 0)
+ {
+ a -= unit * half;
+ }
+
+ if (i == segments - 1)
+ {
+ b += unit * half;
+ }
+ }
+
+ var normal = new Vector2(-unit.Y, unit.X) * half;
+ pieces.Add(Oriented([a + normal, b + normal, b - normal, a - normal]));
+ }
+
+ var joins = contour.Closed ? count : count - 2;
+ var firstJoin = contour.Closed ? 0 : 1;
+ for (var j = 0; j < joins; j++)
+ {
+ pieces.Add(Disc(points[firstJoin + j], half));
+ }
+
+ if (!contour.Closed && cap == LineCap.Round)
+ {
+ pieces.Add(Disc(points[0], half));
+ pieces.Add(Disc(points[count - 1], half));
+ }
+ }
+
+ private static Vector2[] Disc(Vector2 centre, float radius)
+ {
+ var n = PathBuilder.ArcSteps(radius, 360, 0.05f);
+ var result = new Vector2[n];
+ for (var i = 0; i < n; i++)
+ {
+ var t = i * 2 * MathF.PI / n;
+ result[i] = centre + new Vector2(radius * MathF.Cos(t), radius * MathF.Sin(t));
+ }
+
+ return Oriented(result);
+ }
+
+ /// The polygon turning clockwise on screen (positive signed area with y downwards), reversed if needed.
+ private static Vector2[] Oriented(Vector2[] polygon)
+ {
+ var area = 0f;
+ for (var i = 0; i < polygon.Length; i++)
+ {
+ var p = polygon[i];
+ var q = polygon[(i + 1) % polygon.Length];
+ area += (p.X * q.Y) - (q.X * p.Y);
+ }
+
+ if (area < 0)
+ {
+ Array.Reverse(polygon);
+ }
+
+ return polygon;
+ }
+
+ /// The complementary error function, |error| < 1.5e-7 (Abramowitz and Stegun 7.1.26).
+ private static float Erfc(float x)
+ {
+ var z = MathF.Abs(x);
+ var t = 1 / (1 + (0.3275911f * z));
+ var poly = t * (0.254829592f + (t * (-0.284496736f + (t * (1.421413741f + (t * (-1.453152027f + (t * 1.061405429f))))))));
+ var erfcAbs = poly * MathF.Exp(-z * z);
+ return x >= 0 ? erfcAbs : 2 - erfcAbs;
+ }
+}
diff --git a/src/Febe.Core/Drawing/Color.cs b/src/Febe.Core/Drawing/Color.cs
new file mode 100644
index 0000000..cfb6a39
--- /dev/null
+++ b/src/Febe.Core/Drawing/Color.cs
@@ -0,0 +1,27 @@
+namespace Febe.Core.Drawing;
+
+/// A colour of the drawing code: 8-bit red, green, blue and alpha, not premultiplied.
+public readonly record struct Color(byte R, byte G, byte B, byte A = 255)
+{
+ public static Color Transparent => new(0, 0, 0, 0);
+
+ public static Color White => new(255, 255, 255);
+
+ public static Color Black => new(0, 0, 0);
+
+ /// An opaque colour from 0xRRGGBB.
+ public static Color FromRgb(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
+
+ /// The same colour with another alpha.
+ public Color WithAlpha(byte alpha) => this with { A = alpha };
+
+ ///
+ /// The colour of the way from this one to (0 this, 1 the other),
+ /// truncated to whole levels; the alpha of this colour.
+ ///
+ public Color Mix(Color other, float t) => new(
+ (byte)(R + ((other.R - R) * t)),
+ (byte)(G + ((other.G - G) * t)),
+ (byte)(B + ((other.B - B) * t)),
+ A);
+}
diff --git a/src/Febe.Core/Drawing/CoverageRasterizer.cs b/src/Febe.Core/Drawing/CoverageRasterizer.cs
new file mode 100644
index 0000000..7c8cecc
--- /dev/null
+++ b/src/Febe.Core/Drawing/CoverageRasterizer.cs
@@ -0,0 +1,237 @@
+using System.Buffers;
+using System.Numerics;
+
+namespace Febe.Core.Drawing;
+
+///
+/// Exact anti-aliased coverage of polygons by signed areas. Every edge adds, in each row it crosses, the area between
+/// itself and the right side of the row to the cells it touches, as differences between neighbouring cells; the running
+/// sum of a row is then, for each pixel, the winding of the area it covers, weighted by the fraction covered. The
+/// coverage of a pixel is that sum, in absolute value, at most 1: the non-zero rule, exact for every pixel that no two
+/// edges share and very close for the others. Works in a window of the canvas (the shape's bounds), one row of
+/// differences per row of the window.
+///
+internal sealed class CoverageRasterizer : IDisposable
+{
+ private float[] _cells = [];
+ private int _stride;
+
+ /// Left column of the window in the canvas.
+ public int Left { get; private set; }
+
+ /// Top row of the window in the canvas.
+ public int Top { get; private set; }
+
+ public int Width { get; private set; }
+
+ public int Height { get; private set; }
+
+ /// Starts a new shape in the window (, , width × height).
+ public void Reset(int left, int top, int width, int height)
+ {
+ Left = left;
+ Top = top;
+ Width = width;
+ Height = height;
+ _stride = width + 2;
+ var length = _stride * height;
+ if (_cells.Length < length)
+ {
+ if (_cells.Length > 0)
+ {
+ ArrayPool.Shared.Return(_cells);
+ }
+
+ _cells = ArrayPool.Shared.Rent(length);
+ }
+
+ _cells.AsSpan(0, length).Clear();
+ }
+
+ /// Adds the edges of a closed polygon (canvas pixels; the last point joins the first).
+ public void AddPolygon(ReadOnlySpan points)
+ {
+ for (var i = 0; i < points.Length; i++)
+ {
+ AddEdge(points[i], points[(i + 1) % points.Length]);
+ }
+ }
+
+ /// Adds one edge, in canvas pixels.
+ public void AddEdge(Vector2 from, Vector2 to)
+ {
+ var x0 = from.X - Left;
+ var y0 = from.Y - Top;
+ var x1 = to.X - Left;
+ var y1 = to.Y - Top;
+ if (y0 == y1 || float.IsNaN(x0) || float.IsNaN(x1) || float.IsNaN(y0) || float.IsNaN(y1))
+ {
+ return;
+ }
+
+ // Outside the window on the left an edge covers everything to its right in the window: the same as an edge
+ // on the left border. On the right it covers nothing in the window: the right border. So the parts of the edge
+ // beyond either border are moved onto it.
+ // The direction of the edge is its winding: the pieces keep it.
+ float w = Width;
+ if (x0 >= 0 && x1 >= 0 && x0 <= w && x1 <= w)
+ {
+ Accumulate(x0, y0, x1, y1);
+ return;
+ }
+
+ if (MathF.Max(x0, x1) <= 0 || MathF.Min(x0, x1) >= w)
+ {
+ var border = MathF.Max(x0, x1) <= 0 ? 0 : w;
+ Accumulate(border, y0, border, y1);
+ return;
+ }
+
+ // Cut where the edge crosses the borders, in order along the edge.
+ Span cuts = stackalloc float[4];
+ var count = 0;
+ cuts[count++] = 0;
+ foreach (var border in (ReadOnlySpan)[0, w])
+ {
+ var t = (border - x0) / (x1 - x0);
+ if (t > 0 && t < 1)
+ {
+ cuts[count++] = t;
+ }
+ }
+
+ cuts[count++] = 1;
+ cuts[1..(count - 1)].Sort();
+ for (var i = 0; i + 1 < count; i++)
+ {
+ var ta = cuts[i];
+ var tb = cuts[i + 1];
+ var ya = y0 + ((y1 - y0) * ta);
+ var yb = y0 + ((y1 - y0) * tb);
+ var xa = x0 + ((x1 - x0) * ta);
+ var xb = x0 + ((x1 - x0) * tb);
+ var middle = (xa + xb) / 2;
+ if (middle <= 0)
+ {
+ Accumulate(0, ya, 0, yb);
+ }
+ else if (middle >= w)
+ {
+ Accumulate(w, ya, w, yb);
+ }
+ else
+ {
+ Accumulate(Math.Clamp(xa, 0, w), ya, Math.Clamp(xb, 0, w), yb);
+ }
+ }
+ }
+
+ /// The coverage of row of the window (0-1 for each of its columns).
+ public void Coverage(int y, Span output)
+ {
+ var row = _cells.AsSpan(y * _stride, Width);
+ var sum = 0f;
+ for (var x = 0; x < row.Length; x++)
+ {
+ sum += row[x];
+ var c = MathF.Abs(sum);
+ output[x] = c > 1 ? 1 : c;
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_cells.Length > 0)
+ {
+ ArrayPool.Shared.Return(_cells);
+ _cells = [];
+ }
+ }
+
+ /// One edge with 0 ≤ x ≤ Width, the rows outside the window ignored.
+ private void Accumulate(float x0, float y0, float x1, float y1)
+ {
+ if (y0 == y1)
+ {
+ return;
+ }
+
+ var direction = 1f;
+ if (y0 > y1)
+ {
+ (x0, y0, x1, y1) = (x1, y1, x0, y0);
+ direction = -1f;
+ }
+
+ var dxdy = (x1 - x0) / (y1 - y0);
+ var x = x0;
+ if (y0 < 0)
+ {
+ x -= y0 * dxdy;
+ y0 = 0;
+ }
+
+ var end = MathF.Min(y1, Height);
+ if (y0 >= end)
+ {
+ return;
+ }
+
+ float w = Width;
+ var cells = _cells;
+ var firstRow = (int)y0;
+ var lastRow = (int)MathF.Ceiling(end);
+ for (var y = firstRow; y < lastRow; y++)
+ {
+ var top = MathF.Max(y, y0);
+ var bottom = MathF.Min(y + 1, end);
+ var dy = bottom - top;
+ var next = x + (dxdy * dy);
+ var d = dy * direction;
+ var left = Math.Clamp(MathF.Min(x, next), 0, w);
+ var right = Math.Clamp(MathF.Max(x, next), 0, w);
+ var row = y * _stride;
+ var leftCell = (int)left;
+ var rightCell = (int)MathF.Ceiling(right);
+ if (rightCell <= leftCell + 1)
+ {
+ // The edge stays inside one cell: the part of the cell right of it, then the full row beyond.
+ var middle = (0.5f * (x + next)) - leftCell;
+ middle = Math.Clamp(middle, 0, 1);
+ cells[row + leftCell] += d - (d * middle);
+ cells[row + leftCell + 1] += d * middle;
+ }
+ else
+ {
+ // Across several cells the covered part grows linearly: a triangle in the first cell, a constant step
+ // in the middle ones, the complement of a triangle in the last one.
+ var s = 1 / (right - left);
+ var leftFraction = left - leftCell;
+ var firstArea = 0.5f * s * (1 - leftFraction) * (1 - leftFraction);
+ var rightFraction = right - (rightCell - 1);
+ var lastGap = 0.5f * s * rightFraction * rightFraction;
+ cells[row + leftCell] += d * firstArea;
+ if (rightCell == leftCell + 2)
+ {
+ cells[row + leftCell + 1] += d * (1 - firstArea - lastGap);
+ }
+ else
+ {
+ var second = s * (1.5f - leftFraction);
+ cells[row + leftCell + 1] += d * (second - firstArea);
+ for (var cell = leftCell + 2; cell < rightCell - 1; cell++)
+ {
+ cells[row + cell] += d * s;
+ }
+
+ var beforeLast = second + ((rightCell - leftCell - 3) * s);
+ cells[row + rightCell - 1] += d * (1 - beforeLast - lastGap);
+ }
+
+ cells[row + rightCell] += d * lastGap;
+ }
+
+ x = next;
+ }
+ }
+}
diff --git a/src/Febe.Core/Drawing/Matrix2D.cs b/src/Febe.Core/Drawing/Matrix2D.cs
new file mode 100644
index 0000000..f91ad4c
--- /dev/null
+++ b/src/Febe.Core/Drawing/Matrix2D.cs
@@ -0,0 +1,28 @@
+using System.Numerics;
+
+namespace Febe.Core.Drawing;
+
+///
+/// An affine transform of the plane: x' = M11·x + M21·y + M31, y' = M12·x + M22·y + M32 (the layout of
+/// , which does the arithmetic). Transforms compose as with a canvas: the last one applied
+/// to the canvas acts first on the shapes drawn.
+///
+public readonly record struct Matrix2D(Matrix3x2 Value)
+{
+ public static Matrix2D Identity => new(Matrix3x2.Identity);
+
+ public static Matrix2D Translation(float x, float y) => new(Matrix3x2.CreateTranslation(x, y));
+
+ public static Matrix2D Scaling(float x, float y) => new(Matrix3x2.CreateScale(x, y));
+
+ /// A rotation by around the origin, clockwise on screen (y grows downwards).
+ public static Matrix2D Rotation(float degrees) => new(Matrix3x2.CreateRotation(degrees * MathF.PI / 180f));
+
+ /// The transform that applies first and then this one.
+ public Matrix2D Then(Matrix2D inner) => new(inner.Value * Value);
+
+ public Vector2 Apply(Vector2 point) => Vector2.Transform(point, Value);
+
+ /// How much the transform enlarges lengths, on average (the square root of the area scale).
+ public float LengthScale => MathF.Sqrt(MathF.Abs(Value.GetDeterminant()));
+}
diff --git a/src/Febe.Core/Drawing/PathBuilder.cs b/src/Febe.Core/Drawing/PathBuilder.cs
new file mode 100644
index 0000000..8a08af1
--- /dev/null
+++ b/src/Febe.Core/Drawing/PathBuilder.cs
@@ -0,0 +1,275 @@
+using System.Numerics;
+
+namespace Febe.Core.Drawing;
+
+///
+/// The outline of a shape: contours of straight lines, quadratic and cubic Bézier curves and elliptic arcs. Angles are
+/// in degrees, measured from the positive x axis towards the positive y axis (clockwise on screen, where y grows
+/// downwards). A filled path covers the points of non-zero winding; contours drawn the other way round cut holes.
+///
+public sealed class PathBuilder
+{
+ private readonly List _commands = [];
+
+ private enum Kind
+ {
+ Move,
+ Line,
+ Quad,
+ Cubic,
+ Arc,
+ Close,
+ }
+
+ /// Whether nothing was added.
+ public bool IsEmpty => _commands.Count == 0;
+
+ /// Starts a new contour at (, ).
+ public PathBuilder MoveTo(float x, float y)
+ {
+ _commands.Add(new Command(Kind.Move, new Vector2(x, y)));
+ return this;
+ }
+
+ /// A straight line to (, ).
+ public PathBuilder LineTo(float x, float y)
+ {
+ _commands.Add(new Command(Kind.Line, new Vector2(x, y)));
+ return this;
+ }
+
+ /// A quadratic Bézier curve through the control point (cx, cy) to (x, y).
+ public PathBuilder QuadTo(float cx, float cy, float x, float y)
+ {
+ _commands.Add(new Command(Kind.Quad, new Vector2(cx, cy), new Vector2(x, y)));
+ return this;
+ }
+
+ /// A cubic Bézier curve through the control points (c1x, c1y) and (c2x, c2y) to (x, y).
+ public PathBuilder CubicTo(float c1x, float c1y, float c2x, float c2y, float x, float y)
+ {
+ _commands.Add(new Command(Kind.Cubic, new Vector2(c1x, c1y), new Vector2(c2x, c2y), new Vector2(x, y)));
+ return this;
+ }
+
+ ///
+ /// A new contour along the ellipse inscribed in the rectangle (, )–
+ /// (, ), from for
+ /// (negative: the other way round).
+ ///
+ public PathBuilder AddArc(float left, float top, float right, float bottom, float startDegrees, float sweepDegrees)
+ {
+ var centre = new Vector2((left + right) / 2, (top + bottom) / 2);
+ _commands.Add(new Command(Kind.Arc, centre, new Vector2((right - left) / 2, (bottom - top) / 2), new Vector2(startDegrees, sweepDegrees)));
+ return this;
+ }
+
+ /// Closes the current contour with a straight line back to its start.
+ public PathBuilder Close()
+ {
+ _commands.Add(new Command(Kind.Close, default));
+ return this;
+ }
+
+ /// A closed ellipse centred on (cx, cy), clockwise on screen (or the other way round).
+ public PathBuilder AddEllipse(float cx, float cy, float rx, float ry, bool clockwise = true)
+ {
+ _commands.Add(new Command(Kind.Arc, new Vector2(cx, cy), new Vector2(rx, ry), new Vector2(0, clockwise ? 360 : -360)));
+ return Close();
+ }
+
+ /// A closed circle.
+ public PathBuilder AddCircle(float cx, float cy, float r, bool clockwise = true) => AddEllipse(cx, cy, r, r, clockwise);
+
+ /// A closed rectangle, clockwise on screen (or the other way round).
+ public PathBuilder AddRect(float x, float y, float width, float height, bool clockwise = true)
+ {
+ if (clockwise)
+ {
+ MoveTo(x, y).LineTo(x + width, y).LineTo(x + width, y + height).LineTo(x, y + height);
+ }
+ else
+ {
+ MoveTo(x, y).LineTo(x, y + height).LineTo(x + width, y + height).LineTo(x + width, y);
+ }
+
+ return Close();
+ }
+
+ /// A closed rectangle with corners rounded to quarter circles of .
+ public PathBuilder AddRoundRect(float x, float y, float width, float height, float radius)
+ {
+ var r = Math.Clamp(radius, 0, Math.Min(Math.Abs(width), Math.Abs(height)) / 2);
+ if (r <= 0)
+ {
+ return AddRect(x, y, width, height);
+ }
+
+ var right = x + width;
+ var bottom = y + height;
+ MoveTo(x + r, y);
+ LineTo(right - r, y);
+ ArcSegment(right - r, y + r, r, 270, 90);
+ LineTo(right, bottom - r);
+ ArcSegment(right - r, bottom - r, r, 0, 90);
+ LineTo(x + r, bottom);
+ ArcSegment(x + r, bottom - r, r, 90, 90);
+ LineTo(x, y + r);
+ ArcSegment(x + r, y + r, r, 180, 90);
+ return Close();
+ }
+
+ /// A closed polygon through (x0, y0, x1, y1, ...).
+ public PathBuilder AddPolygon(ReadOnlySpan points)
+ {
+ if (points.Length < 6 || points.Length % 2 != 0)
+ {
+ throw new ArgumentException("A polygon needs at least three points, two numbers each.", nameof(points));
+ }
+
+ MoveTo(points[0], points[1]);
+ for (var i = 2; i < points.Length; i += 2)
+ {
+ LineTo(points[i], points[i + 1]);
+ }
+
+ return Close();
+ }
+
+ ///
+ /// The contours as polylines in canvas pixels, the curves divided finely enough that no chord strays more than
+ /// pixels from the curve. Chords fall inside a convex curve, so a circle loses about
+ /// 4·tolerance / (3·radius) of its area: 0.01 keeps that near half a percent down to a radius of 2.5 pixels.
+ ///
+ internal List Flatten(Matrix2D transform, float tolerance = 0.01f)
+ {
+ var result = new List();
+ var scale = Math.Max(transform.LengthScale, 1e-6f);
+ List? points = null;
+ var start = Vector2.Zero;
+ var current = Vector2.Zero;
+
+ void Finish(bool closed)
+ {
+ if (points is { Count: >= 2 })
+ {
+ result.Add(new Polyline([.. points], closed));
+ }
+
+ points = null;
+ }
+
+ void Add(Vector2 user)
+ {
+ points ??= [transform.Apply(current)];
+ points.Add(transform.Apply(user));
+ current = user;
+ }
+
+ foreach (var c in _commands)
+ {
+ switch (c.Kind)
+ {
+ case Kind.Move:
+ Finish(closed: false);
+ start = current = c.A;
+ points = [transform.Apply(c.A)];
+ break;
+ case Kind.Line:
+ Add(c.A);
+ break;
+ case Kind.Quad:
+ {
+ var p0 = current;
+ var n = CurveSteps(Vector2.Distance(p0, c.A) + Vector2.Distance(c.A, c.B), scale, tolerance);
+ for (var i = 1; i <= n; i++)
+ {
+ var t = i / (float)n;
+ var u = 1 - t;
+ Add((u * u * p0) + (2 * u * t * c.A) + (t * t * c.B));
+ }
+
+ break;
+ }
+
+ case Kind.Cubic:
+ {
+ var p0 = current;
+ var n = CurveSteps(Vector2.Distance(p0, c.A) + Vector2.Distance(c.A, c.B) + Vector2.Distance(c.B, c.C), scale, tolerance);
+ for (var i = 1; i <= n; i++)
+ {
+ var t = i / (float)n;
+ var u = 1 - t;
+ Add((u * u * u * p0) + (3 * u * u * t * c.A) + (3 * u * t * t * c.B) + (t * t * t * c.C));
+ }
+
+ break;
+ }
+
+ case Kind.Arc:
+ {
+ var (centre, radii, startDegrees, sweepDegrees) = (c.A, c.B, c.C.X, c.C.Y);
+ var first = centre + Ellipse(radii, startDegrees);
+ if (!c.Continues)
+ {
+ Finish(closed: false);
+ start = current = first;
+ points = [transform.Apply(first)];
+ }
+ else
+ {
+ Add(first);
+ }
+
+ var n = ArcSteps(Math.Max(Math.Abs(radii.X), Math.Abs(radii.Y)) * scale, sweepDegrees, tolerance);
+ for (var i = 1; i <= n; i++)
+ {
+ Add(centre + Ellipse(radii, startDegrees + (sweepDegrees * i / n)));
+ }
+
+ break;
+ }
+
+ case Kind.Close:
+ Finish(closed: true);
+ current = start;
+ break;
+ }
+ }
+
+ Finish(closed: false);
+ return result;
+ }
+
+ /// An arc that continues the current contour (used by the rounded rectangle).
+ private void ArcSegment(float cx, float cy, float r, float startDegrees, float sweepDegrees) =>
+ _commands.Add(new Command(Kind.Arc, new Vector2(cx, cy), new Vector2(r, r), new Vector2(startDegrees, sweepDegrees)) { Continues = true });
+
+ private static Vector2 Ellipse(Vector2 radii, float degrees)
+ {
+ var t = degrees * MathF.PI / 180f;
+ return new Vector2(radii.X * MathF.Cos(t), radii.Y * MathF.Sin(t));
+ }
+
+ private static int CurveSteps(float controlLength, float scale, float tolerance)
+ {
+ var pixels = controlLength * scale;
+ return Math.Clamp((int)MathF.Ceiling(MathF.Sqrt(pixels / (8 * tolerance))), 1, 1024);
+ }
+
+ /// Chords of an arc of radius , each with a sagitta of at most the tolerance.
+ internal static int ArcSteps(float radiusPixels, float sweepDegrees, float tolerance)
+ {
+ var sweep = MathF.Abs(sweepDegrees) * MathF.PI / 180f;
+ var maxStep = radiusPixels <= tolerance ? MathF.PI / 2 : 2 * MathF.Acos(1 - (tolerance / radiusPixels));
+ return Math.Clamp((int)MathF.Ceiling(sweep / Math.Max(maxStep, 1e-4f)), 2, 4096);
+ }
+
+ private readonly record struct Command(Kind Kind, Vector2 A, Vector2 B = default, Vector2 C = default)
+ {
+ public bool Continues { get; init; }
+ }
+}
+
+/// A flattened contour in canvas pixels.
+internal readonly record struct Polyline(Vector2[] Points, bool Closed);
diff --git a/src/Febe.Core/Febe.Core.csproj b/src/Febe.Core/Febe.Core.csproj
index ce06a54..4ed7bb1 100644
--- a/src/Febe.Core/Febe.Core.csproj
+++ b/src/Febe.Core/Febe.Core.csproj
@@ -1,9 +1,6 @@
-
-
-
diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs
index d250a4b..4914a82 100644
--- a/src/Febe.Core/Import/ContentAnalysis.cs
+++ b/src/Febe.Core/Import/ContentAnalysis.cs
@@ -67,7 +67,7 @@ internal static class ContentAnalysis
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
ct.ThrowIfCancellationRequested();
- (width, height, hash) = Decode(() => new MemoryStream(bytes, writable: false));
+ (width, height, hash) = Decode(bytes);
}
else
{
@@ -80,6 +80,21 @@ internal static class ContentAnalysis
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
}
+ /// Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC).
+ private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes)
+ {
+ try
+ {
+ var size = ImageDecoding.ReadSize(bytes);
+ return (size?.Width, size?.Height, PerceptualHash.Compute(new MemoryStream(bytes, writable: false)));
+ }
+ catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
+ {
+ return (null, null, null);
+ }
+ }
+
+ /// The same for a photo too large to keep in memory, opened twice.
private static (int? Width, int? Height, ulong? Hash) Decode(Func open)
{
try
@@ -96,9 +111,9 @@ internal static class ContentAnalysis
using var again = open();
return (width, height, PerceptualHash.Compute(again));
}
- catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OutOfMemoryException)
+ catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
{
- return (null, null, null); // a format SkiaSharp cannot decode (e.g. HEIC): no size, no hash
+ return (null, null, null); // formats Febe cannot decode (e.g. HEIC) already give nulls: no size, no hash
}
}
diff --git a/src/Febe.Core/Import/ImportPreview.cs b/src/Febe.Core/Import/ImportPreview.cs
index 5b699c9..f9d66fc 100644
--- a/src/Febe.Core/Import/ImportPreview.cs
+++ b/src/Febe.Core/Import/ImportPreview.cs
@@ -1,34 +1,20 @@
using Febe.Core.Library;
-using SkiaSharp;
namespace Febe.Core.Import;
/// In-memory previews of source photos for the comparison panel (nothing is written to disk).
internal static class ImportPreview
{
- private const int JpegQuality = 82;
-
/// A JPEG of the image, upright, at most pixels; null when it cannot be decoded.
public static byte[]? RenderJpeg(Stream encodedImage, int longSide)
{
- using var bitmap = ImageDecoding.DecodeUpright(encodedImage, longSide);
- if (bitmap is null)
+ using var image = ThumbnailStore.DecodeFor(encodedImage, longSide);
+ if (image is null)
{
return null;
}
- var scale = Math.Min(1.0, (double)longSide / Math.Max(bitmap.Width, bitmap.Height));
- var width = Math.Max(1, (int)Math.Round(bitmap.Width * scale));
- var height = Math.Max(1, (int)Math.Round(bitmap.Height * scale));
- using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- surface.Canvas.Clear(SKColors.White);
- using (var image = SKImage.FromBitmap(bitmap))
- {
- surface.Canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
- }
-
- using var snapshot = surface.Snapshot();
- using var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, JpegQuality);
- return data?.ToArray();
+ using var small = ThumbnailStore.Render(image, longSide);
+ return ThumbnailStore.Jpeg(small);
}
}
diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md
index 3ed596b..dd0861c 100644
--- a/src/Febe.Core/Import/LEGGIMI.md
+++ b/src/Febe.Core/Import/LEGGIMI.md
@@ -159,7 +159,7 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per
## Limiti noti
-- HEIC/HEIF: si riconoscono, ma SkiaSharp (pacchetto Linux senza dipendenze) non li decodifica: niente dimensioni,
+- HEIC/HEIF: si riconoscono, ma i codec di Febe (PNG, JPEG, GIF, BMP, WebP) non li decodificano: niente dimensioni,
impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica.
- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella
scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice.
diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs
index f0941c4..6be35a5 100644
--- a/src/Febe.Core/Library/ImageDecoding.cs
+++ b/src/Febe.Core/Library/ImageDecoding.cs
@@ -1,10 +1,11 @@
-using SkiaSharp;
+using Febe.Core.Codecs.Images;
namespace Febe.Core.Library;
///
-/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it,
-/// decoding directly at a reduced size to save memory and time.
+/// Decodes images with the in-house codecs (: JPEG, PNG, GIF, BMP, WebP), applying the
+/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is
+/// enough, which saves memory and time.
///
internal static class ImageDecoding
{
@@ -14,118 +15,110 @@ internal static class ImageDecoding
///
public const long MaxDecodedPixels = 100_000_000;
+ /// Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it).
+ public const long MaxFileBytes = 512L * 1024 * 1024;
+
+ private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels };
+
///
- /// Decodes an image upright, as premultiplied RGBA. When is given the codec may
- /// decode at a lower resolution, but never below that long side (unless the image is smaller).
- /// Returns null when the content is not a decodable image.
+ /// Decodes an image upright, as straight RGBA. When is given the codec may decode
+ /// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the
+ /// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large).
///
- public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null)
+ public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null)
{
ArgumentNullException.ThrowIfNull(stream);
- using var data = SKData.Create(stream);
- if (data is null || data.IsEmpty)
+ return ReadAll(stream) is { } data ? DecodeUpright(data, minLongSide) : null;
+ }
+
+ /// Like , from bytes already in memory.
+ public static RgbaImage? DecodeUpright(ReadOnlyMemory data, int? minLongSide = null)
+ {
+ if (data.IsEmpty)
{
return null;
}
- using var codec = SKCodec.Create(data);
- if (codec is null)
+ RgbaImage? stored = null;
+ try
+ {
+ ImageInfo info;
+ stored = minLongSide is { } min && min > 0
+ ? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true)
+ : ImageDecoder.Decode(data, out info, Limits, pooled: true);
+ var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true);
+ if (!ReferenceEquals(upright, stored))
+ {
+ stored.Dispose();
+ }
+
+ stored = null;
+ return upright;
+ }
+ catch (ImageDecodeException)
{
return null;
}
-
- var size = ChooseDecodeSize(codec, minLongSide);
- if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0)
+ finally
{
- return null;
+ stored?.Dispose();
}
-
- var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
- var decoded = new SKBitmap(info);
- var result = codec.GetPixels(info, decoded.GetPixels());
- if (result is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
- {
- decoded.Dispose();
- return null;
- }
-
- return Orient(decoded, codec.EncodedOrigin);
}
/// Dimensions of an image as displayed (orientation applied), without decoding the pixels.
public static (int Width, int Height)? ReadSize(Stream stream)
{
ArgumentNullException.ThrowIfNull(stream);
- using var codec = SKCodec.Create(stream);
- if (codec is null)
+ return ReadAll(stream) is { } data ? ReadSize(data) : null;
+ }
+
+ /// Like , from bytes already in memory.
+ public static (int Width, int Height)? ReadSize(ReadOnlyMemory data)
+ {
+ if (data.IsEmpty)
{
return null;
}
- var (w, h) = (codec.Info.Width, codec.Info.Height);
- return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
+ try
+ {
+ var info = ImageDecoder.Identify(data, Limits);
+ return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
+ }
+ catch (ImageDecodeException)
+ {
+ return null;
+ }
}
- private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
+ private static byte[]? ReadAll(Stream stream)
{
- var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
- if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min)
+ if (stream.CanSeek)
{
- return full;
- }
-
- var best = full;
- foreach (var scale in new[] { 0.5f, 0.25f, 0.125f })
- {
- var scaled = codec.GetScaledDimensions(scale);
- if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min)
+ var remaining = stream.Length - stream.Position;
+ if (remaining <= 0 || remaining > MaxFileBytes)
{
- break;
+ return null;
}
- best = scaled;
+ var bytes = new byte[remaining];
+ stream.ReadExactly(bytes);
+ return bytes;
}
- return best;
- }
-
- private static bool SwapsAxes(SKEncodedOrigin origin) =>
- origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom;
-
- private static SKBitmap Orient(SKBitmap source, SKEncodedOrigin origin)
- {
- if (origin is SKEncodedOrigin.TopLeft or SKEncodedOrigin.Default)
+ using var copy = new MemoryStream();
+ var buffer = new byte[81920];
+ int read;
+ while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
- return source;
+ if (copy.Length + read > MaxFileBytes)
+ {
+ return null;
+ }
+
+ copy.Write(buffer, 0, read);
}
- float w = source.Width, h = source.Height;
- var swap = SwapsAxes(origin);
- var outW = swap ? source.Height : source.Width;
- var outH = swap ? source.Width : source.Height;
-
- // Each matrix maps a source pixel (x, y) to its upright position.
- var matrix = origin switch
- {
- SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1),
- SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1),
- SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1),
- SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1),
- SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1),
- SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1),
- SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1),
- _ => SKMatrix.Identity,
- };
-
- var upright = new SKBitmap(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Premul));
- using (var canvas = new SKCanvas(upright))
- {
- canvas.Clear(SKColors.Transparent);
- canvas.SetMatrix(in matrix);
- canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
- }
-
- source.Dispose();
- return upright;
+ return copy.Length == 0 ? null : copy.ToArray();
}
}
diff --git a/src/Febe.Core/Library/PerceptualHash.cs b/src/Febe.Core/Library/PerceptualHash.cs
index 63b88f5..cbf7ee6 100644
--- a/src/Febe.Core/Library/PerceptualHash.cs
+++ b/src/Febe.Core/Library/PerceptualHash.cs
@@ -1,5 +1,5 @@
using System.Numerics;
-using SkiaSharp;
+using Febe.Core.Codecs.Images;
namespace Febe.Core.Library;
@@ -38,6 +38,9 @@ public static class PerceptualHash
private const int Size = 32;
private const int Low = 8;
+ /// A JPEG is decoded reduced, but never below this long side.
+ private const int MinDecodedSide = 256;
+
private static readonly double[,] Cosines = BuildCosines();
/// Hamming distance between two hashes (0–64).
@@ -50,8 +53,8 @@ public static class PerceptualHash
public static ulong? Compute(Stream encodedImage)
{
ArgumentNullException.ThrowIfNull(encodedImage);
- using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
- return bitmap is null ? null : Compute(bitmap);
+ using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide);
+ return image is null ? null : Compute(image);
}
/// Hash of an image file; null when it is not a decodable image.
@@ -61,17 +64,11 @@ public static class PerceptualHash
return Compute(stream);
}
- /// Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).
- internal static ulong Compute(SKBitmap bitmap)
+ /// Hash of a decoded image (any size), upright as it is shown.
+ internal static ulong Compute(RgbaImage image)
{
- ArgumentNullException.ThrowIfNull(bitmap);
- using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul
- ? null
- : bitmap.Copy(SKColorType.Rgba8888);
- var source = rgba ?? bitmap;
- var grey = Luminance(source);
- var small = AreaResample(grey, source.Width, source.Height, Size, Size);
- return HashOf(small);
+ ArgumentNullException.ThrowIfNull(image);
+ return HashOf(AreaResample(image, Size, Size));
}
/// The hash of a 32×32 grey image (row-major).
@@ -123,50 +120,37 @@ public static class PerceptualHash
return hash;
}
- /// Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.
- private static double[] Luminance(SKBitmap bitmap)
+ ///
+ /// The grey levels (0–255, over white: ) of an image reduced to dw × dh by area
+ /// averaging, one source row at a time (memory: one row and dw × source height values).
+ ///
+ internal static double[] AreaResample(RgbaImage image, int dw, int dh)
{
- var width = bitmap.Width;
- var height = bitmap.Height;
- var result = new double[width * height];
- var pixels = bitmap.GetPixelSpan();
- var rowBytes = bitmap.RowBytes;
- for (var y = 0; y < height; y++)
- {
- var row = pixels.Slice(y * rowBytes, width * 4);
- for (var x = 0; x < width; x++)
- {
- var r = row[x * 4];
- var g = row[(x * 4) + 1];
- var b = row[(x * 4) + 2];
- var a = row[(x * 4) + 3];
- var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha)
- result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white));
- }
- }
-
- return result;
- }
-
- /// Area-averaging resample with exact fractional coverage (no aliasing when reducing).
- internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh)
- {
- var horizontal = new double[dw * sh];
+ var sw = image.Width;
+ var sh = image.Height;
var xs = Weights(sw, dw);
+ var horizontal = new double[dw * sh];
+ var grey = new double[sw];
for (var y = 0; y < sh; y++)
{
+ ImageGray.LumaOverWhite(image.GetRow(y), grey);
for (var dx = 0; dx < dw; dx++)
{
double sum = 0;
foreach (var (index, weight) in xs[dx])
{
- sum += source[(y * sw) + index] * weight;
+ sum += grey[index] * weight;
}
horizontal[(y * dw) + dx] = sum;
}
}
+ return Vertical(horizontal, sh, dw, dh);
+ }
+
+ private static double[] Vertical(double[] horizontal, int sh, int dw, int dh)
+ {
var result = new double[dw * dh];
var ys = Weights(sh, dh);
for (var dy = 0; dy < dh; dy++)
diff --git a/src/Febe.Core/Library/ThumbnailStore.cs b/src/Febe.Core/Library/ThumbnailStore.cs
index 7dceb90..a3951f6 100644
--- a/src/Febe.Core/Library/ThumbnailStore.cs
+++ b/src/Febe.Core/Library/ThumbnailStore.cs
@@ -1,4 +1,5 @@
-using SkiaSharp;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Drawing;
namespace Febe.Core.Library;
@@ -54,13 +55,14 @@ public sealed class ThumbnailStore
return true;
}
- using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
- if (bitmap is null)
+ using var image = DecodeFor(encodedImage, LongSide);
+ if (image is null)
{
return false;
}
- WriteJpeg(target, Render(bitmap, LongSide));
+ using var thumbnail = Render(image, LongSide);
+ WriteJpeg(target, thumbnail);
return true;
}
@@ -94,26 +96,20 @@ public sealed class ThumbnailStore
}
const int width = 270, height = LongSide; // 9:16, like stories and reels
- using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- var canvas = surface.Canvas;
- canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4));
- using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill })
+ using var tile = new RgbaImage(width, height);
+ using (var canvas = new Canvas(tile))
{
- canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
- }
+ var background = new Color(0xE4, 0xE4, 0xE4);
+ canvas.Clear(background);
+ canvas.FillCircle(width / 2f, height / 2f, 34, new Color(0x9A, 0x9A, 0x9A));
- using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill })
- {
- // A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp.
- var cx = width / 2f + 4;
+ // The play sign: a triangle pointing right, a little right of the centre to look centred.
+ var cx = (width / 2f) + 4;
var cy = height / 2f;
- SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
- canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
+ canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background);
}
- using var image = surface.Snapshot();
- using var bitmap = SKBitmap.FromImage(image);
- WriteJpeg(path, bitmap.Copy());
+ WriteJpeg(path, tile);
return path;
}
@@ -125,67 +121,66 @@ public sealed class ThumbnailStore
{
ArgumentNullException.ThrowIfNull(source);
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
- using var decoded = ImageDecoding.DecodeUpright(source, longSide);
+ using var decoded = DecodeFor(source, longSide);
if (decoded is null)
{
return null;
}
using var small = Render(decoded, longSide);
- using var pixmap = small.PeekPixels();
- if (pixmap is null)
- {
- return null;
- }
-
- using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
- return data?.ToArray();
+ return Jpeg(small);
}
- private static SKBitmap Render(SKBitmap source, int longSide)
+ ///
+ /// Decodes an image upright for a picture of pixels. A JPEG may be shrunk while decoding,
+ /// but only down to twice that size: the last step is left to Lanczos, since the codec's 8 × 8 block averages would
+ /// show at almost 1:1. Null when the content cannot be decoded.
+ ///
+ internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
+ ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
+
+ ///
+ /// The image reduced to on its long side (Lanczos, never enlarged) and seen over white,
+ /// since JPEG has no alpha. Always a new pooled image, which the caller disposes.
+ ///
+ internal static RgbaImage Render(RgbaImage source, int longSide)
{
- var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
- var width = Math.Max(1, (int)Math.Round(source.Width * scale));
- var height = Math.Max(1, (int)Math.Round(source.Height * scale));
- var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- using var canvas = new SKCanvas(result);
- canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white
- using var image = SKImage.FromBitmap(source);
- canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
+ var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, longSide);
+ var result = ImageResampler.Resize(source, width, height, pooled: true);
+ ImageBackground.Flatten(result, Color.White);
return result;
}
- private static void WriteJpeg(string target, SKBitmap bitmap)
+ /// The JPEG of a thumbnail: quality , chroma 4:2:0.
+ internal static byte[] Jpeg(RgbaImage image) =>
+ JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = JpegQuality, Subsampling = JpegSubsampling.Ratio420 });
+
+ private static void WriteJpeg(string target, RgbaImage image)
{
- using (bitmap)
+ var data = Jpeg(image);
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
+ try
{
- Directory.CreateDirectory(Path.GetDirectoryName(target)!);
- var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
+ using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
+ {
+ file.Write(data);
+ }
+
try
{
- using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel."))
- using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality))
- ?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita."))
- using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
- {
- data.SaveTo(file);
- }
-
- try
- {
- File.Move(temp, target, overwrite: false);
- }
- catch (IOException) when (File.Exists(target))
- {
- // Created meanwhile by another task: same content.
- }
+ File.Move(temp, target, overwrite: false);
}
- finally
+ catch (IOException) when (File.Exists(target))
{
- if (File.Exists(temp))
- {
- File.Delete(temp);
- }
+ // Created meanwhile by another task: same content.
+ }
+ }
+ finally
+ {
+ if (File.Exists(temp))
+ {
+ File.Delete(temp);
}
}
}
diff --git a/src/Febe.Desktop.Core/BrandIcon.cs b/src/Febe.Desktop.Core/BrandIcon.cs
index 88c3e38..45b6eec 100644
--- a/src/Febe.Desktop.Core/BrandIcon.cs
+++ b/src/Febe.Desktop.Core/BrandIcon.cs
@@ -1,11 +1,12 @@
using System.Buffers.Binary;
-using SkiaSharp;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Drawing;
namespace Febe.Desktop.Core;
///
/// The brand mark of appendix C — a rounded square in the accent colour with a ring and a dot, a body and its moon —
-/// drawn with SkiaSharp at any size, the same way the SVG describes it:
+/// drawn with Febe's own rasteriser () at any size, the same way the SVG describes it:
///
/// <rect width="32" height="32" rx="8" fill="#0F5C8C"/>
/// <circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/>
@@ -17,57 +18,32 @@ public static class BrandMark
/// The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer.
public static IReadOnlyList IconSizes { get; } = [16, 24, 32, 48, 64, 128, 256];
- private static readonly SKColor Accent = new(0x0F, 0x5C, 0x8C);
+ private static readonly Color Accent = Color.FromRgb(0x0F5C8C);
- /// The mark as a square bitmap of pixels, premultiplied BGRA, transparent corners.
- public static SKBitmap Render(int size)
+ /// The mark as a square image of pixels, straight RGBA, transparent corners.
+ public static RgbaImage Render(int size)
{
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024);
- var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Premul));
- using var canvas = new SKCanvas(bitmap);
- canvas.Clear(SKColors.Transparent);
- var scale = size / 32f;
- canvas.Scale(scale);
- using (var square = new SKPaint { Color = Accent, IsAntialias = true, Style = SKPaintStyle.Fill })
- {
- canvas.DrawRoundRect(new SKRect(0, 0, 32, 32), 8, 8, square);
- }
-
- using (var ring = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 2.6f })
- {
- canvas.DrawCircle(14.5f, 17.5f, 7.4f, ring);
- }
-
- using (var moon = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Fill })
- {
- canvas.DrawCircle(23.2f, 8.8f, 3.1f, moon);
- }
-
- canvas.Flush();
- return bitmap;
+ var image = new RgbaImage(size, size);
+ using var canvas = new Canvas(image);
+ canvas.Scale(size / 32f);
+ canvas.FillRoundRect(0, 0, 32, 32, 8, Accent);
+ canvas.StrokeCircle(14.5f, 17.5f, 7.4f, 2.6f, Color.White);
+ canvas.FillCircle(23.2f, 8.8f, 3.1f, Color.White);
+ return image;
}
/// The multi-size Windows icon () of the mark, as the bytes of an .ico file.
public static byte[] RenderIcon()
{
- var images = new List();
- try
+ var images = new List();
+ foreach (var size in IconSizes)
{
- foreach (var size in IconSizes)
- {
- images.Add(Render(size));
- }
+ images.Add(Render(size));
+ }
- return IcoWriter.Write(images);
- }
- finally
- {
- foreach (var image in images)
- {
- image.Dispose();
- }
- }
+ return IcoWriter.Write(images);
}
}
@@ -86,7 +62,7 @@ public static class IcoWriter
private const int BitmapInfoHeader = 40;
/// The .ico bytes of square (1 to 256 pixels), in the order given.
- public static byte[] Write(IReadOnlyList images)
+ public static byte[] Write(IReadOnlyList images)
{
ArgumentNullException.ThrowIfNull(images);
if (images.Count is 0 or > ushort.MaxValue)
@@ -167,41 +143,48 @@ public static class IcoWriter
return entries;
}
- /// The image of an entry as a bitmap (DIB or PNG), for comparisons.
- public static SKBitmap Decode(ReadOnlySpan ico, IcoEntry entry)
+ /// The image of an entry (DIB or PNG) as straight RGBA, for comparisons.
+ public static RgbaImage Decode(ReadOnlySpan ico, IcoEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var data = ico.Slice(entry.Offset, entry.Length);
if (entry.IsPng)
{
- return SKBitmap.Decode(data.ToArray()) ?? throw new InvalidDataException("PNG dell'icona non leggibile.");
+ try
+ {
+ return PngDecoder.Decode(data.ToArray());
+ }
+ catch (ImageDecodeException ex)
+ {
+ throw new InvalidDataException("PNG dell'icona non leggibile.", ex);
+ }
}
var size = entry.Size;
- var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Unpremul));
+ var image = new RgbaImage(size, size);
var pixels = data[BitmapInfoHeader..];
for (var y = 0; y < size; y++)
{
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
+ var target = image.GetRow(y);
for (var x = 0; x < size; x++)
{
- bitmap.SetPixel(x, y, new SKColor(row[(x * 4) + 2], row[(x * 4) + 1], row[x * 4], row[(x * 4) + 3]));
+ target[x * 4] = row[(x * 4) + 2];
+ target[(x * 4) + 1] = row[(x * 4) + 1];
+ target[(x * 4) + 2] = row[x * 4];
+ target[(x * 4) + 3] = row[(x * 4) + 3];
}
}
- return bitmap;
+ return image;
}
private static ReadOnlySpan PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
- private static byte[] Png(SKBitmap image)
- {
- using var data = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new InvalidOperationException("Codifica PNG non riuscita.");
- return data.ToArray();
- }
+ private static byte[] Png(RgbaImage image) => PngEncoder.Encode(image, new PngEncoderOptions { ColorMode = PngColorMode.Rgba });
/// A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask.
- private static byte[] Dib(SKBitmap image)
+ private static byte[] Dib(RgbaImage image)
{
var size = image.Width;
var maskStride = ((size + 31) / 32) * 4;
@@ -223,13 +206,13 @@ public static class IcoWriter
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
for (var x = 0; x < size; x++)
{
- // GetPixel gives straight (not premultiplied) alpha, as icons want it.
+ // Straight (not premultiplied) alpha, as icons want it.
var c = image.GetPixel(x, y);
- row[x * 4] = c.Blue;
- row[(x * 4) + 1] = c.Green;
- row[(x * 4) + 2] = c.Red;
- row[(x * 4) + 3] = c.Alpha;
- if (c.Alpha == 0)
+ row[x * 4] = c.B;
+ row[(x * 4) + 1] = c.G;
+ row[(x * 4) + 2] = c.R;
+ row[(x * 4) + 3] = c.A;
+ if (c.A == 0)
{
// Transparent pixels are also set in the AND mask, for the readers that ignore the alpha channel.
var maskRow = mask.Slice((size - 1 - y) * maskStride, maskStride);
diff --git a/src/Febe.Desktop/Febe.Desktop.csproj b/src/Febe.Desktop/Febe.Desktop.csproj
index 4e44622..5171830 100644
--- a/src/Febe.Desktop/Febe.Desktop.csproj
+++ b/src/Febe.Desktop/Febe.Desktop.csproj
@@ -2,7 +2,7 @@
WinExe
@@ -47,8 +47,8 @@
+ cartella Dati; i simboli e la documentazione XML dei pacchetti non servono a chi usa Febe. Niente di tutto
+ questo esce accanto all'eseguibile. -->
diff --git a/src/Febe.Desktop/Febe.ico b/src/Febe.Desktop/Febe.ico
index 9665cdb..a8f622c 100644
Binary files a/src/Febe.Desktop/Febe.ico and b/src/Febe.Desktop/Febe.ico differ
diff --git a/src/Febe.Server/Febe.Server.csproj b/src/Febe.Server/Febe.Server.csproj
index ce6b18b..fda03d6 100644
--- a/src/Febe.Server/Febe.Server.csproj
+++ b/src/Febe.Server/Febe.Server.csproj
@@ -12,7 +12,6 @@
-
diff --git a/src/Febe.Web/Demo/DemoImages.cs b/src/Febe.Web/Demo/DemoImages.cs
index 933d615..01f7dbc 100644
--- a/src/Febe.Web/Demo/DemoImages.cs
+++ b/src/Febe.Web/Demo/DemoImages.cs
@@ -1,4 +1,6 @@
-using SkiaSharp;
+using System.Numerics;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Drawing;
namespace Febe.Web.Demo;
@@ -35,8 +37,8 @@ public static class DemoImages
{
ArgumentOutOfRangeException.ThrowIfLessThan(width, 16);
ArgumentOutOfRangeException.ThrowIfLessThan(height, 16);
- using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- using (var canvas = new SKCanvas(bitmap))
+ var image = new RgbaImage(width, height);
+ using (var canvas = new Canvas(image))
{
var painter = new Painter(canvas, width, height, new Random(seed * 7919 + (int)subject));
switch (subject)
@@ -59,64 +61,54 @@ public static class DemoImages
}
}
- using var image = SKImage.FromBitmap(bitmap);
- using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality);
- return data.ToArray();
+ return JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality });
}
- private sealed class Painter(SKCanvas canvas, float w, float h, Random random)
+ /// A rectangle by its edges.
+ private readonly record struct Box(float Left, float Top, float Right, float Bottom);
+
+ private sealed class Painter(Canvas canvas, float w, float h, Random random)
{
private float R(float min, float max) => min + ((float)random.NextDouble() * (max - min));
private T Pick(params T[] items) => items[random.Next(items.Length)];
- private static SKColor C(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
+ private static Color C(uint rgb) => Color.FromRgb(rgb);
- private static SKColor Mix(SKColor a, SKColor b, float t) => new(
- (byte)(a.Red + ((b.Red - a.Red) * t)),
- (byte)(a.Green + ((b.Green - a.Green) * t)),
- (byte)(a.Blue + ((b.Blue - a.Blue) * t)));
+ private static Color Mix(Color a, Color b, float t) => a.Mix(b, t).WithAlpha(255);
- private void Gradient(SKRect rect, SKColor top, SKColor bottom)
+ private void Gradient(Box rect, Color top, Color bottom) =>
+ canvas.FillRect(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, new LinearGradientBrush(new Vector2(0, rect.Top), new Vector2(0, rect.Bottom), [top, bottom]));
+
+ private void Fill(PathBuilder path, Color color) => canvas.Fill(path, color);
+
+ private void Circle(float x, float y, float r, Color color) => canvas.FillCircle(x, y, r, color);
+
+ private void Oval(float cx, float cy, float rx, float ry, Color color, float rotate = 0)
{
- using var paint = new SKPaint { IsAntialias = true };
- paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, rect.Top), new SKPoint(0, rect.Bottom), [top, bottom], null, SKShaderTileMode.Clamp);
- canvas.DrawRect(rect, paint);
- }
-
- private void Fill(SKPathBuilder builder, SKColor color)
- {
- using var path = builder.Detach();
- using var paint = new SKPaint { IsAntialias = true, Color = color, Style = SKPaintStyle.Fill };
- canvas.DrawPath(path, paint);
- }
-
- private void Circle(float x, float y, float r, SKColor color)
- {
- using var paint = new SKPaint { IsAntialias = true, Color = color };
- canvas.DrawCircle(x, y, r, paint);
- }
-
- private void Oval(float cx, float cy, float rx, float ry, SKColor color, float rotate = 0)
- {
- using var paint = new SKPaint { IsAntialias = true, Color = color };
canvas.Save();
canvas.Translate(cx, cy);
- canvas.RotateDegrees(rotate);
- canvas.DrawOval(new SKRect(-rx, -ry, rx, ry), paint);
+ canvas.Rotate(rotate);
+ canvas.FillEllipse(0, 0, rx, ry, color);
canvas.Restore();
}
- private void Rect(float x, float y, float rw, float rh, SKColor color, float radius = 0)
+ private void Rect(float x, float y, float rw, float rh, Color color, float radius = 0)
{
- using var paint = new SKPaint { IsAntialias = true, Color = color };
- canvas.DrawRoundRect(new SKRect(x, y, x + rw, y + rh), radius, radius, paint);
+ if (radius > 0)
+ {
+ canvas.FillRoundRect(x, y, rw, rh, radius, color);
+ }
+ else
+ {
+ canvas.FillRect(x, y, rw, rh, color);
+ }
}
/// A soft ridge across the picture at height , filled down to the bottom.
- private static SKPathBuilder Ridge(float w, float h, float baseY, float amplitude, int bumps, float phase)
+ private static PathBuilder Ridge(float w, float h, float baseY, float amplitude, int bumps, float phase)
{
- var path = new SKPathBuilder();
+ var path = new PathBuilder();
path.MoveTo(0, h);
const int steps = 48;
for (var i = 0; i <= steps; i++)
@@ -138,23 +130,23 @@ public static class DemoImages
var cx = R(-0.1f, 1.1f) * w;
var cy = R(top, bottom) * h;
var size = R(0.07f, 0.13f) * Math.Max(w, h);
- var color = new SKColor(255, 255, 255, (byte)R(200, 240));
+ var color = new Color(255, 255, 255, (byte)R(200, 240));
Oval(cx, cy, size, size * 0.32f, color);
Oval(cx - (size * 0.35f), cy + (size * 0.05f), size * 0.55f, size * 0.25f, color);
- Oval(cx + (size * 0.25f), cy - (size * 0.12f), size * 0.5f, size * 0.3f, new SKColor(255, 255, 255, (byte)R(220, 250)));
+ Oval(cx + (size * 0.25f), cy - (size * 0.12f), size * 0.5f, size * 0.3f, new Color(255, 255, 255, (byte)R(220, 250)));
}
}
- private void Cypress(float x, float baseY, float size, SKColor color)
+ private void Cypress(float x, float baseY, float size, Color color)
{
Oval(x, baseY - (size * 0.55f), size * 0.22f, size * 0.55f, color);
- Rect(x - (size * 0.03f), baseY - (size * 0.08f), size * 0.06f, size * 0.12f, Mix(color, SKColors.Black, 0.3f));
+ Rect(x - (size * 0.03f), baseY - (size * 0.08f), size * 0.06f, size * 0.12f, Mix(color, Color.Black, 0.3f));
}
public void Hills(bool road)
{
var sky = Pick(C(0x6FA8DC), C(0x7FB3E0), C(0x5E9BD6), C(0x8DBBE3));
- Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.45f));
+ Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.45f));
Clouds(0.08f, 0.35f, random.Next(2, 5));
var greens = Pick(
new[] { C(0x8DB867), C(0x6E9E4C), C(0x4F8A3E), C(0x3C7232) },
@@ -164,7 +156,7 @@ public static class DemoImages
for (var layer = 0; layer < 4; layer++)
{
var y = baseY + (layer * h * R(0.08f, 0.12f));
- using var ridge = Ridge(w, h, y, h * R(0.015f, 0.04f), random.Next(1, 4), R(0, 6));
+ var ridge = Ridge(w, h, y, h * R(0.015f, 0.04f), random.Next(1, 4), R(0, 6));
Fill(ridge, greens[layer]);
if (!road && layer < 3)
{
@@ -178,7 +170,7 @@ public static class DemoImages
if (road)
{
var horizon = baseY + (h * 0.03f);
- using var path = new SKPathBuilder();
+ var path = new PathBuilder();
path.MoveTo(w * 0.47f, horizon);
path.LineTo(w * 0.53f, horizon);
path.LineTo(w * 0.86f, h);
@@ -208,13 +200,13 @@ public static class DemoImages
public void Mountains()
{
var sky = Pick(C(0x5D8FC8), C(0x6E9BD0), C(0x7FA8D6));
- Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.55f));
+ Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.55f));
var ranges = new[] { C(0x8C9BB2), C(0x6F7F99), C(0x56647E) };
for (var r = 0; r < 3; r++)
{
var baseY = h * (0.55f + (r * 0.08f));
var peaks = random.Next(2, 4) + r;
- using var path = new SKPathBuilder();
+ var path = new PathBuilder();
path.MoveTo(0, h);
path.LineTo(0, baseY);
var snow = new List<(float X, float Y, float Half)>();
@@ -239,7 +231,7 @@ public static class DemoImages
{
var depth = (baseY - py) * 0.32f;
var ratio = depth / (baseY - py);
- using var cap = new SKPathBuilder();
+ var cap = new PathBuilder();
cap.MoveTo(px, py);
cap.LineTo(px + (half * ratio), py + depth);
cap.LineTo(px + (half * ratio * 0.3f), py + (depth * 0.8f));
@@ -260,7 +252,7 @@ public static class DemoImages
var x = R(0, 1) * w;
var size = h * R(0.06f, 0.11f);
var y = groundY + (h * R(-0.01f, 0.08f));
- using var tree = new SKPathBuilder();
+ var tree = new PathBuilder();
tree.MoveTo(x, y - size);
tree.LineTo(x + (size * 0.28f), y);
tree.LineTo(x - (size * 0.28f), y);
@@ -273,16 +265,16 @@ public static class DemoImages
{
var top = Pick(C(0x3B2A5A), C(0x4A2F63), C(0x2E2350));
var bottom = Pick(C(0xF0784C), C(0xE86A5A), C(0xF29A57));
- Gradient(new SKRect(0, 0, w, h * 0.75f), top, bottom);
+ Gradient(new Box(0, 0, w, h * 0.75f), top, bottom);
var sunX = w * R(0.35f, 0.65f);
var sunY = h * R(0.5f, 0.6f);
var r = Math.Min(w, h) * R(0.09f, 0.13f);
- Circle(sunX, sunY, r * 1.8f, new SKColor(255, 220, 170, 60));
+ Circle(sunX, sunY, r * 1.8f, new Color(255, 220, 170, 60));
Circle(sunX, sunY, r, C(0xFBE3B0));
var hills = new[] { C(0x6B4A73), C(0x4E3A63), C(0x35294D) };
for (var i = 0; i < 3; i++)
{
- using var ridge = Ridge(w, h, h * (0.66f + (i * 0.09f)), h * R(0.02f, 0.05f), random.Next(1, 3), R(0, 6));
+ var ridge = Ridge(w, h, h * (0.66f + (i * 0.09f)), h * R(0.02f, 0.05f), random.Next(1, 3), R(0, 6));
Fill(ridge, hills[i]);
}
}
@@ -291,32 +283,31 @@ public static class DemoImages
{
var sky = Pick(C(0x8CC4E8), C(0x7BB8E2), C(0x9CCDEB));
var horizon = h * R(0.42f, 0.55f);
- Gradient(new SKRect(0, 0, w, horizon), Mix(sky, C(0x4F8FC8), 0.3f), Mix(sky, SKColors.White, 0.5f));
+ Gradient(new Box(0, 0, w, horizon), Mix(sky, C(0x4F8FC8), 0.3f), Mix(sky, Color.White, 0.5f));
Clouds(0.08f, 0.25f, random.Next(0, 3));
var water = Pick(C(0x2AA3C1), C(0x1F8FB3), C(0x31A9BE));
var sand = random.Next(3) == 0;
- Gradient(new SKRect(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f));
- using (var wave = new SKPaint { IsAntialias = true, Color = new SKColor(255, 255, 255, 110), StrokeWidth = Math.Max(2, h * 0.004f), StrokeCap = SKStrokeCap.Round })
+ Gradient(new Box(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f));
+ var foam = new Color(255, 255, 255, 110);
+ var waveWidth = Math.Max(2, h * 0.004f);
+ for (var i = 0; i < 9; i++)
{
- for (var i = 0; i < 9; i++)
- {
- var y = horizon + ((h - horizon) * R(0.1f, 0.9f));
- var x = R(0.05f, 0.85f) * w;
- canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, wave);
- }
+ var y = horizon + ((h - horizon) * R(0.1f, 0.9f));
+ var x = R(0.05f, 0.85f) * w;
+ canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, waveWidth, foam, LineCap.Round);
}
if (sand)
{
- using var shore = Ridge(w, h, h * 0.9f, h * 0.02f, 2, R(0, 6));
+ var shore = Ridge(w, h, h * 0.9f, h * 0.02f, 2, R(0, 6));
Fill(shore, C(0xE9D8B4));
}
var bx = w * R(0.3f, 0.65f);
var by = horizon + ((h - horizon) * R(0.2f, 0.4f));
var s = Math.Min(w, h) * R(0.06f, 0.09f);
- using (var sail = new SKPathBuilder())
{
+ var sail = new PathBuilder();
sail.MoveTo(bx, by - s);
sail.LineTo(bx + (s * 0.45f), by - (s * 0.1f));
sail.LineTo(bx, by - (s * 0.1f));
@@ -324,8 +315,8 @@ public static class DemoImages
Fill(sail, C(0xF6F6F4));
}
- using (var sail2 = new SKPathBuilder())
{
+ var sail2 = new PathBuilder();
sail2.MoveTo(bx - (s * 0.04f), by - (s * 0.85f));
sail2.LineTo(bx - (s * 0.04f), by - (s * 0.12f));
sail2.LineTo(bx - (s * 0.38f), by - (s * 0.12f));
@@ -333,8 +324,8 @@ public static class DemoImages
Fill(sail2, C(0xE0533F));
}
- using (var hull = new SKPathBuilder())
{
+ var hull = new PathBuilder();
hull.MoveTo(bx - (s * 0.5f), by - (s * 0.05f));
hull.LineTo(bx + (s * 0.55f), by - (s * 0.05f));
hull.LineTo(bx + (s * 0.4f), by + (s * 0.1f));
@@ -346,10 +337,10 @@ public static class DemoImages
public void City()
{
- Gradient(new SKRect(0, 0, w, h), C(0x1E1B3A), Pick(C(0x3E2F5C), C(0x4A3566), C(0x2F2A52)));
+ Gradient(new Box(0, 0, w, h), C(0x1E1B3A), Pick(C(0x3E2F5C), C(0x4A3566), C(0x2F2A52)));
for (var i = 0; i < 70; i++)
{
- Circle(R(0, 1) * w, R(0, 0.45f) * h, R(0.6f, 1.8f), new SKColor(255, 255, 255, (byte)R(60, 180)));
+ Circle(R(0, 1) * w, R(0, 0.45f) * h, R(0.6f, 1.8f), new Color(255, 255, 255, (byte)R(60, 180)));
}
for (var layer = 0; layer < 2; layer++)
@@ -384,7 +375,7 @@ public static class DemoImages
public void Leaves(bool flowers)
{
var dark = Pick(C(0x1F4D33), C(0x24533A), C(0x2B5C3C));
- Gradient(new SKRect(0, 0, w, h), Mix(dark, SKColors.Black, 0.1f), dark);
+ Gradient(new Box(0, 0, w, h), Mix(dark, Color.Black, 0.1f), dark);
var greens = new[] { C(0x3E8C4E), C(0x5AA45A), C(0x2F7A45), C(0x78B861), C(0x4C9A6A), C(0x8BC46A) };
var size = Math.Max(w, h);
for (var i = 0; i < 46; i++)
@@ -395,11 +386,10 @@ public static class DemoImages
var angle = R(0, 360);
var color = greens[random.Next(greens.Length)];
Oval(cx, cy, rx, rx * 0.42f, color, angle);
- using var vein = new SKPaint { IsAntialias = true, Color = Mix(color, SKColors.White, 0.25f), StrokeWidth = Math.Max(1.5f, size * 0.003f) };
canvas.Save();
canvas.Translate(cx, cy);
- canvas.RotateDegrees(angle);
- canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, vein);
+ canvas.Rotate(angle);
+ canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, Math.Max(1.5f, size * 0.003f), Mix(color, Color.White, 0.25f));
canvas.Restore();
}
@@ -426,21 +416,16 @@ public static class DemoImages
{
var table = Pick(C(0xE9E6E1), C(0xEFEBE4), C(0xDCD7CF));
Rect(0, 0, w, h, table);
- using (var line = new SKPaint { IsAntialias = true, Color = Mix(table, SKColors.Black, 0.08f), StrokeWidth = Math.Max(2, w * 0.004f) })
+ var grooves = Mix(table, Color.Black, 0.08f);
+ for (var y = h * 0.12f; y < h; y += h * 0.16f)
{
- for (var y = h * 0.12f; y < h; y += h * 0.16f)
- {
- canvas.DrawLine(0, y, w, y + (h * 0.01f), line);
- }
+ canvas.DrawLine(0, y, w, y + (h * 0.01f), Math.Max(2, w * 0.004f), grooves);
}
var r = Math.Min(w, h) * R(0.28f, 0.34f);
var cx = w * R(0.42f, 0.55f);
var cy = h * R(0.48f, 0.58f);
- using (var shadow = new SKPaint { IsAntialias = true, Color = new SKColor(0, 0, 0, 40), MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, r * 0.06f) })
- {
- canvas.DrawCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, shadow);
- }
+ canvas.FillBlurredCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, r * 0.06f, new Color(0, 0, 0, 40));
Circle(cx, cy, r, C(0xFAFAF8));
Circle(cx, cy, r * 0.78f, C(0xF0EEEA));
@@ -458,24 +443,23 @@ public static class DemoImages
var cr = Math.Min(w, h) * 0.085f;
Circle(cupX, cupY, cr, C(0xF5F3EF));
Circle(cupX, cupY, cr * 0.75f, C(0x5B3A26));
- using var fork = new SKPaint { IsAntialias = true, Color = C(0xC9C6C0), StrokeWidth = Math.Max(3, w * 0.008f), StrokeCap = SKStrokeCap.Round };
- canvas.DrawLine(cx + (r * 1.18f), cy - (r * 0.5f), cx + (r * 1.18f), cy + (r * 0.75f), fork);
+ canvas.DrawLine(cx + (r * 1.18f), cy - (r * 0.5f), cx + (r * 1.18f), cy + (r * 0.75f), Math.Max(3, w * 0.008f), C(0xC9C6C0), LineCap.Round);
}
public void Portrait()
{
var bg = Pick(C(0xB27FC0), C(0xC98F9B), C(0x8FA8C9), C(0xD3A26F), C(0x7FB8A3), C(0xA88FC7));
- Gradient(new SKRect(0, 0, w, h), Mix(bg, SKColors.White, 0.15f), Mix(bg, SKColors.Black, 0.12f));
+ Gradient(new Box(0, 0, w, h), Mix(bg, Color.White, 0.15f), Mix(bg, Color.Black, 0.12f));
var skin = Pick(C(0xD9A27B), C(0xC88A63), C(0xA86F4D), C(0xE8B996), C(0x8D5A3B));
var hair = Pick(C(0x8A4B2A), C(0x3B2A20), C(0xD8B45A), C(0x5A3A22), C(0x1F1B18));
var shirt = Pick(C(0xA8B04A), C(0x5F8F57), C(0xB84A4A), C(0x4F6FA8), C(0xE0C35A));
var cx = w * 0.5f;
var unit = Math.Min(w, h * 0.8f);
Oval(cx, h * 1.02f, unit * 0.42f, h * 0.32f, shirt);
- Rect(cx - (unit * 0.06f), h * 0.52f, unit * 0.12f, h * 0.16f, Mix(skin, SKColors.Black, 0.08f));
+ Rect(cx - (unit * 0.06f), h * 0.52f, unit * 0.12f, h * 0.16f, Mix(skin, Color.Black, 0.08f));
Oval(cx, h * 0.44f, unit * 0.16f, unit * 0.2f, skin);
- using var top = new SKPathBuilder();
- top.AddArc(new SKRect(cx - (unit * 0.17f), (h * 0.44f) - (unit * 0.22f), cx + (unit * 0.17f), (h * 0.44f) + (unit * 0.04f)), 180, 180);
+ var top = new PathBuilder();
+ top.AddArc(cx - (unit * 0.17f), (h * 0.44f) - (unit * 0.22f), cx + (unit * 0.17f), (h * 0.44f) + (unit * 0.04f), 180, 180);
top.Close();
Fill(top, hair);
}
@@ -484,23 +468,23 @@ public static class DemoImages
{
var wall = Pick(C(0xE5DFCF), C(0xE9E2D2), C(0xDCD6C6));
var floorY = h * R(0.68f, 0.74f);
- Gradient(new SKRect(0, 0, w, floorY), Mix(wall, SKColors.White, 0.2f), wall);
- Gradient(new SKRect(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E));
+ Gradient(new Box(0, 0, w, floorY), Mix(wall, Color.White, 0.2f), wall);
+ Gradient(new Box(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E));
var winX = w * R(0.25f, 0.45f);
var winW = w * R(0.26f, 0.34f);
var winY = h * 0.1f;
var winH = h * 0.38f;
Rect(winX - 6, winY - 6, winW + 12, winH + 12, C(0xF7F7F5));
- Gradient(new SKRect(winX, winY, winX + winW, winY + winH), C(0x9CCBEB), C(0xC9E4F4));
+ Gradient(new Box(winX, winY, winX + winW, winY + winH), C(0x9CCBEB), C(0xC9E4F4));
Rect(winX + (winW / 2) - 3, winY, 6, winH, C(0xF7F7F5));
Rect(winX, winY + (winH / 2) - 3, winW, 6, C(0xF7F7F5));
var sofa = Pick(C(0x6E9F7A), C(0x4E8F86), C(0x8A6A9E), C(0xA05A5A));
var sx = w * R(0.05f, 0.15f);
var sw = w * R(0.48f, 0.58f);
- Rect(sx, floorY - (h * 0.2f), sw, h * 0.12f, Mix(sofa, SKColors.White, 0.15f), 10);
+ Rect(sx, floorY - (h * 0.2f), sw, h * 0.12f, Mix(sofa, Color.White, 0.15f), 10);
Rect(sx, floorY - (h * 0.1f), sw, h * 0.12f, sofa, 10);
var px = w * R(0.75f, 0.85f);
- using var pot = new SKPathBuilder();
+ var pot = new PathBuilder();
pot.MoveTo(px - (w * 0.045f), floorY - (h * 0.08f));
pot.LineTo(px + (w * 0.045f), floorY - (h * 0.08f));
pot.LineTo(px + (w * 0.035f), floorY + (h * 0.01f));
@@ -518,34 +502,34 @@ public static class DemoImages
public void Bokeh()
{
- Gradient(new SKRect(0, 0, w, h), C(0x1B1530), Pick(C(0x2A1E3A), C(0x1E1A2E)));
+ Gradient(new Box(0, 0, w, h), C(0x1B1530), Pick(C(0x2A1E3A), C(0x1E1A2E)));
var colors = new[] { C(0xF2B84B), C(0xE0567A), C(0x6BC5E8), C(0xB06BE0), C(0xF08A4B), C(0x7FD38A) };
var size = Math.Max(w, h);
for (var i = 0; i < 40; i++)
{
var color = colors[random.Next(colors.Length)].WithAlpha((byte)R(90, 200));
- using var paint = new SKPaint { IsAntialias = true, Color = color, MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, size * R(0.004f, 0.012f)) };
- canvas.DrawCircle(R(0, 1) * w, R(0, 1) * h, size * R(0.02f, 0.06f), paint);
+ var sigma = size * R(0.004f, 0.012f);
+ var x = R(0, 1) * w;
+ var y = R(0, 1) * h;
+ canvas.FillBlurredCircle(x, y, size * R(0.02f, 0.06f), sigma, color);
}
}
public void Concert()
{
- Gradient(new SKRect(0, 0, w, h), C(0x14121C), C(0x1E1A2A));
+ Gradient(new Box(0, 0, w, h), C(0x14121C), C(0x1E1A2A));
var beams = new[] { C(0xE04A5A), C(0xF2C14B), C(0x4A7FE0), C(0xA04AE0), C(0x4AC0E0) };
for (var i = 0; i < 5; i++)
{
var x = w * (0.12f + (i * 0.19f)) + R(-0.04f, 0.04f) * w;
var color = beams[random.Next(beams.Length)];
- using var paint = new SKPaint { IsAntialias = true };
- paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)], null, SKShaderTileMode.Clamp);
- using var beam = new SKPathBuilder();
+ var light = new LinearGradientBrush(new Vector2(0, 0), new Vector2(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)]);
+ var beam = new PathBuilder();
beam.MoveTo(x, 0);
beam.LineTo(x + (w * R(-0.12f, 0.12f)) + (w * 0.08f), h * 0.75f);
beam.LineTo(x + (w * R(-0.12f, 0.12f)) - (w * 0.08f), h * 0.75f);
beam.Close();
- using var beamPath = beam.Detach();
- canvas.DrawPath(beamPath, paint);
+ canvas.Fill(beam, light);
}
Rect(0, h * 0.72f, w, h * 0.04f, C(0x2B2838));
@@ -560,7 +544,7 @@ public static class DemoImages
public void Houses()
{
var sky = Pick(C(0x8CC4E8), C(0x9CCDEB));
- Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.4f));
+ Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.4f));
var facades = new[] { C(0xF2C55C), C(0xE88B6A), C(0xF0A3A0), C(0xE5D37A), C(0xD9774F), C(0x9FC7B4), C(0xF4E2B8) };
var x = 0f;
while (x < w)
@@ -569,7 +553,7 @@ public static class DemoImages
var top = h * R(0.12f, 0.4f);
var color = facades[random.Next(facades.Length)];
Rect(x, top, fw, h - top, color);
- Rect(x, top, fw, h * 0.02f, Mix(color, SKColors.Black, 0.2f));
+ Rect(x, top, fw, h * 0.02f, Mix(color, Color.Black, 0.2f));
var cell = fw / 5;
for (var wy = top + (cell * 0.8f); wy < h - cell; wy += cell * 1.4f)
{
diff --git a/src/Febe.Web/Demo/DemoPart2.cs b/src/Febe.Web/Demo/DemoPart2.cs
index 1ce513e..f872d41 100644
--- a/src/Febe.Web/Demo/DemoPart2.cs
+++ b/src/Febe.Web/Demo/DemoPart2.cs
@@ -1,6 +1,8 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
+using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
+using Febe.Core.Drawing;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Api;
@@ -8,7 +10,6 @@ using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.AspNetCore.Http;
-using SkiaSharp;
namespace Febe.Web.Demo;
@@ -90,18 +91,18 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld
const int width = 640;
const int height = 360;
- using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- using (var canvas = new SKCanvas(bitmap))
+ using var frame = new RgbaImage(width, height);
+ using (var canvas = new Canvas(frame))
{
- canvas.Clear(new SKColor(0x1A, 0x1A, 0x1A));
+ canvas.Clear(new Color(0x1A, 0x1A, 0x1A));
var tall = height - 40f;
var wide = tall * 9 / 16;
var gap = 26f;
var left = (width - (3 * wide) - (2 * gap)) / 2;
- using var dim = new SKPaint { Color = new SKColor(0, 0, 0, 110) };
+ var dim = new Color(0, 0, 0, 110);
for (var i = 0; i < files.Count; i++)
{
- using var image = SKImage.FromEncodedData(files[i]);
+ using var image = DecodeOrNull(files[i]);
if (image is null)
{
continue;
@@ -112,18 +113,27 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld
var h = tall * scale;
var x = left + (i * (wide + gap)) + ((wide - w) / 2);
var y = (height - h) / 2;
- var rect = new SKRect(x, y, x + w, y + h);
- canvas.DrawImage(image, rect, new SKSamplingOptions(SKCubicResampler.Mitchell));
+ canvas.DrawImage(image, x, y, w, h);
if (i != 1)
{
- canvas.DrawRect(rect, dim);
+ canvas.FillRect(x, y, w, h, dim);
}
}
}
- using var frame = SKImage.FromBitmap(bitmap);
- using var encoded = frame.Encode(SKEncodedImageFormat.Jpeg, 80);
- return encoded.ToArray();
+ return JpegEncoder.Encode(frame, new JpegEncoderOptions { Quality = 80 });
+ }
+
+ private static RgbaImage? DecodeOrNull(byte[] bytes)
+ {
+ try
+ {
+ return ImageDecoder.Decode(bytes);
+ }
+ catch (ImageDecodeException)
+ {
+ return null;
+ }
}
}
@@ -270,22 +280,22 @@ internal static class DemoDuplicates
/// The picture resized by and recompressed: the same photo saved again, smaller.
public static (byte[] Bytes, int Width, int Height)? Variant(byte[] jpeg, double scale, int quality)
{
- using var image = SKImage.FromEncodedData(jpeg);
- if (image is null)
+ RgbaImage image;
+ try
+ {
+ image = ImageDecoder.Decode(jpeg);
+ }
+ catch (ImageDecodeException)
{
return null;
}
- var width = Math.Max(16, (int)Math.Round(image.Width * scale));
- var height = Math.Max(16, (int)Math.Round(image.Height * scale));
- using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
- using (var canvas = new SKCanvas(bitmap))
+ using (image)
{
- canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell));
+ var width = Math.Max(16, (int)Math.Round(image.Width * scale));
+ var height = Math.Max(16, (int)Math.Round(image.Height * scale));
+ using var resized = ImageResampler.Resize(image, width, height);
+ return (JpegEncoder.Encode(resized, new JpegEncoderOptions { Quality = quality }), width, height);
}
-
- using var result = SKImage.FromBitmap(bitmap);
- using var encoded = result.Encode(SKEncodedImageFormat.Jpeg, quality);
- return (encoded.ToArray(), width, height);
}
}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-about.js b/src/Febe.Web/wwwroot/js/pages/settings-about.js
index 4a54508..e311a41 100644
--- a/src/Febe.Web/wwwroot/js/pages/settings-about.js
+++ b/src/Febe.Web/wwwroot/js/pages/settings-about.js
@@ -1,6 +1,6 @@
// Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the
// statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe
-// carries inside (Archivo OFL, Lucide ISC, SQLite, SkiaSharp, .NET, WebView2).
+// carries inside (Archivo OFL, Lucide ISC, SQLite, .NET, WebView2). Images (codecs, thumbnails, drawing) are Febe's own code.
import { api } from '../core/api.js';
import { h, icon, fill, brand } from '../core/dom.js';
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index d69c491..47ce286 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -817,7 +817,6 @@
{ "nome": "Archivo", "testo": "carattere, SIL Open Font License 1.1", "file": "/caratteri/LICENZA-OFL.txt" },
{ "nome": "Lucide", "testo": "icone, licenza ISC", "file": "/icone/LICENZA-ISC.txt" },
{ "nome": "SQLite e Microsoft.Data.Sqlite", "testo": "database, pubblico dominio e licenza MIT" },
- { "nome": "SkiaSharp", "testo": "miniature e impronte delle immagini, licenza MIT" },
{ "nome": ".NET e ASP.NET Core", "testo": "licenza MIT" },
{ "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" }
],
diff --git a/tests/Febe.Tests/Desktop/IconTests.cs b/tests/Febe.Tests/Desktop/IconTests.cs
index 48870b4..9082e1a 100644
--- a/tests/Febe.Tests/Desktop/IconTests.cs
+++ b/tests/Febe.Tests/Desktop/IconTests.cs
@@ -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;
///
-/// 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 src/Febe.Desktop/Febe.ico must be
/// what the code draws: FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests writes it again.
///
@@ -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(() => IcoWriter.Write([wide]));
Assert.ThrowsExactly(() => IcoWriter.Write([huge]));
Assert.ThrowsExactly(() => 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}");
}
}
diff --git a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs
new file mode 100644
index 0000000..b73f8c1
--- /dev/null
+++ b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs
@@ -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;
+
+///
+/// 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 .
+///
+[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 = "";
+ 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 = "";
+ 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(() => ImageConverter.Convert(png, ImageFormat.Gif));
+ Assert.ThrowsExactly(() => 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(() => 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}");
+ }
+ }
+ }
+ }
+
+ /// Pixels covered by what paints on a transparent canvas: the sum of alpha / 255.
+ private static double Coverage(int width, int height, Action