Codec di casa al posto di SkiaSharp (C1, passo 5)

SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies escono da
Directory.Packages.props e da ogni progetto, per la regola «niente
componenti esterni». Tutto ciò che leggeva, ridimensionava o disegnava
immagini con Skia ora usa codice scritto in casa sulla BCL:

- ImageResampler: Lanczos3 separabile o media per area, alfa
  premoltiplicata, luce lineare facoltativa; ImageGray per l'impronta.
- Il lettore JPEG decodifica ridotto a 1/2, 1/4, 1/8; le miniature
  chiedono almeno il doppio del lato lungo, così l'ultimo passo resta a
  Lanczos e la miniatura resta uguale alla lettura intera.
- ImageOrientation applica l'EXIF in un punto solo (miniature, impronte,
  anteprime, dimensioni mostrate).
- ImageConverter cambia formato fra JPEG, PNG e WebP portando EXIF, ICC,
  XMP e testi, con l'etichetta d'orientamento e i pixel non ruotati;
  PngEncoder scrive anche i testi (tEXt o iTXt).
- Febe.Core.Drawing: rasterizzatore con antialiasing (tracciati,
  riempimenti, tratti, gradienti) per icona, immagini dimostrative,
  riquadro neutro dei video, foto del sito di prova e prove. Febe.ico
  rigenerata.
- ThumbnailStore legge anche i BMP a 24 bit, come quelli del decoder
  video del ramo funzione/decoder-h264.

Le impronte salvate restano confrontabili (390 su 393 campioni identiche,
le altre a distanza 2, soglia 6): nessun ricalcolo. Un PNG o JPEG
troncato ora non ha miniatura né impronta. Documenti, elenco dei
componenti della pagina «Informazioni» e decisioni aggiornati; nuove
prove per ridimensionamento, orientamento, lettura ridotta, conversione
con metadati, testi PNG e rasterizzatore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:02:03 +01:00
1 parent b4383a6110
commit d6a6a68496
47 files changed
+3391 -562

No files matched your search

@@ -0,0 +1,220 @@
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>Options of <see cref="ImageConverter"/>.</summary>
public sealed record ImageConversionOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static ImageConversionOptions Default { get; } = new();
/// <summary>Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026).</summary>
public int JpegQuality { get; init; } = 92;
/// <summary>Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible.</summary>
public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444;
/// <summary>What transparent areas become in a JPEG target, which has no alpha.</summary>
public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White;
/// <summary>Limits of the decoding of the source.</summary>
public ImageLimits Limits { get; init; } = ImageLimits.Default;
}
/// <summary>What <see cref="ImageConverter.Convert"/> made.</summary>
/// <param name="Data">The converted file.</param>
/// <param name="Source">The format of the source.</param>
/// <param name="Target">The format written.</param>
/// <param name="Width">Width as stored (the orientation is not applied: the tag is copied).</param>
/// <param name="Height">Height as stored.</param>
/// <param name="Lossy">Whether pixels may differ from the source's (a JPEG target).</param>
/// <param name="Metadata">The metadata written.</param>
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
public sealed record ImageConversionResult(
byte[] Data,
ImageFormat Source,
ImageFormat Target,
int Width,
int Height,
bool Lossy,
ImageMetadata Metadata,
IReadOnlyList<string> NotCarried);
/// <summary>
/// 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 <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first
/// frame only, and say so.
/// </summary>
public static class ImageConverter
{
/// <summary>The formats a conversion can write.</summary>
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
public static ImageConversionResult Convert(ReadOnlyMemory<byte> 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<string>();
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<string>();
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);
}
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
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<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
{
var result = new List<ImageText>(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;
}
}
/// <summary>Composites an image over a plain colour.</summary>
public static class ImageBackground
{
/// <summary>Every pixel of <paramref name="image"/> seen over <paramref name="background"/>, opaque, in place.</summary>
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;
}
}
}
@@ -38,6 +38,53 @@ public static class ImageDecoder
var other => throw NotSupported(other),
};
/// <summary>Decodes an image to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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);
}
}
/// <summary>
/// Decodes an image no smaller than <paramref name="minLongSide"/> 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 <see cref="Identify"/> returns (the full size). The result may still need resizing.
/// </summary>
public static RgbaImage DecodeAtLeast(ReadOnlyMemory<byte> 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.")
+33
View File
@@ -0,0 +1,33 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Grey levels of RGBA pixels.</summary>
public static class ImageGray
{
/// <summary>
/// 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.
/// </summary>
public static void LumaOverWhite(ReadOnlySpan<byte> rgba, Span<double> 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));
}
}
}
@@ -0,0 +1,70 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
public static class ImageOrientation
{
/// <summary>Whether the orientation swaps width and height (5-8).</summary>
public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8;
/// <summary>The size of an image as shown, from its stored size.</summary>
public static (int Width, int Height) ShownSize(int width, int height, int orientation) =>
SwapsAxes(orientation) ? (height, width) : (width, height);
/// <summary>
/// The image turned upright. Returns <paramref name="stored"/> itself for orientation 1 (or any value outside
/// 1-8); otherwise a new image (pooled when asked), and <paramref name="stored"/> is left as it is.
/// </summary>
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;
}
}
@@ -0,0 +1,433 @@
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Febe.Core.Codecs.Images;
/// <summary>The filter <see cref="ImageResampler"/> weighs the source pixels with.</summary>
public enum ResampleFilter
{
/// <summary>
/// The Lanczos window of three lobes, sinc(x) sinc(x/3) for |x| &lt; 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).
/// </summary>
Lanczos3,
/// <summary>
/// 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.
/// </summary>
Area,
}
/// <summary>Options of <see cref="ImageResampler"/>.</summary>
public sealed record ResampleOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static ResampleOptions Default { get; } = new();
public ResampleFilter Filter { get; init; } = ResampleFilter.Lanczos3;
/// <summary>
/// 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).
/// </summary>
public bool LinearLight { get; init; }
}
/// <summary>
/// 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.
/// </summary>
public static class ImageResampler
{
/// <summary><paramref name="source"/> resized to <paramref name="width"/> × <paramref name="height"/>.</summary>
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;
}
}
/// <summary>
/// The size that fits <paramref name="width"/> × <paramref name="height"/> inside a square of
/// <paramref name="longSide"/>, keeping the proportions (rounded, at least 1); the same size when it already fits.
/// </summary>
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<Vector4>.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<byte> row, Span<Vector4> 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<Vector4> input, Span<Vector4> 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<Vector4> accumulator, ReadOnlySpan<Vector4> row, float weight)
{
var acc = MemoryMarshal.Cast<Vector4, float>(accumulator);
var add = MemoryMarshal.Cast<Vector4, float>(row);
var i = 0;
if (Vector.IsHardwareAccelerated && acc.Length >= Vector<float>.Count)
{
var w = new Vector<float>(weight);
var accVectors = MemoryMarshal.Cast<float, Vector<float>>(acc);
var addVectors = MemoryMarshal.Cast<float, Vector<float>>(add);
for (var v = 0; v < accVectors.Length; v++)
{
accVectors[v] += addVectors[v] * w;
}
i = accVectors.Length * Vector<float>.Count;
}
for (; i < acc.Length; i++)
{
acc[i] += add[i] * weight;
}
}
private static void StoreRow(ReadOnlySpan<Vector4> row, Span<byte> 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;
}
/// <summary>
/// The weights of one direction: for each target index the first source index, how many follow and their
/// weights (summing to 1), <see cref="MaxTaps"/> slots per target index. Source indices outside the image are
/// folded onto the nearest edge pixel.
/// </summary>
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<double> 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);
}
}
/// <summary>Conversions between 8-bit sRGB and linear light (IEC 61966-2-1).</summary>
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;
}
}
}
+44
View File
@@ -73,6 +73,50 @@ internal static class JpegDct
}
}
/// <summary>
/// Like <see cref="Inverse"/>, but writes the block reduced by 2^<paramref name="shift"/> (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.
/// </summary>
public static void InverseReduced(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> 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<byte> 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);
}
}
}
/// <summary>
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
/// not yet quantized.
@@ -49,6 +49,23 @@ public static class JpegDecoder
return image;
}
/// <summary>
/// Decodes a JPEG reduced by 2^<paramref name="reduction"/> in each direction (0 full size, 1 half, 2 quarter,
/// 3 eighth; sizes rounded up), with what <see cref="Identify"/> 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.
/// </summary>
public static RgbaImage DecodeReduced(ReadOnlyMemory<byte> 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;
}
/// <summary>
/// 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).
@@ -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;
@@ -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;
+14 -11
View File
@@ -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<byte>.Shared.Rent(Width + 1);
buffers[i] = ArrayPool<byte>.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
}
/// <summary>
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="Width"/> samples. A ratio
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="OutputWidth"/> 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.
/// </summary>
@@ -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;
+46 -5
View File
@@ -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; } = [];
/// <summary>
/// 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 &gt;&gt; shift)² samples, the means of its squares of samples (only its DC term at an
/// eighth). Set before <see cref="Run"/>; a lossless file is always decoded at full size.
/// </summary>
public int ScaleShift
{
get => _scaleShift;
set => _scaleShift = Math.Clamp(value, 0, 3);
}
/// <summary>Width of the decoded image: <see cref="Width"/> reduced by <see cref="ScaleShift"/>, rounded up.</summary>
public int OutputWidth => Reduce(Width);
/// <summary>Height of the decoded image: <see cref="Height"/> reduced by <see cref="ScaleShift"/>, rounded up.</summary>
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<byte>.Shared.Rent(samples);
c.Plane = ArrayPool<byte>.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);
}
}
}
/// <summary>The samples of one block into the plane of its component, at the scale of <see cref="ScaleShift"/>.</summary>
private void TransformBlock(JpegComponent c, byte[] plane, ReadOnlySpan<short> block, int bx, int by, ReadOnlySpan<byte> 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);
}
}
/// <summary>12-bit samples to 8 bits, rounded.</summary>
private static class Twelve
{
+73
View File
@@ -59,6 +59,12 @@ public sealed record PngEncoderOptions
/// <summary>XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».</summary>
public string? Xmp { get; init; }
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<ImageText> Texts { get; init; } = [];
}
/// <summary>
@@ -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();
}
/// <summary>Whether <paramref name="keyword"/> can name a PNG text chunk: 1-79 printable Latin-1, no outer or double spaces.</summary>
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] == ' ')
+118
View File
@@ -0,0 +1,118 @@
using System.Numerics;
namespace Febe.Core.Drawing;
/// <summary>What fills a shape: one colour or a gradient.</summary>
public abstract class Brush
{
private protected Brush()
{
}
/// <summary>
/// The colours of <paramref name="output"/>.Length pixels of row <paramref name="y"/> from column
/// <paramref name="x0"/>: red, green and blue 0-255, alpha 0-1, not premultiplied. <paramref name="toUser"/> maps
/// canvas pixels back to the coordinates the brush was defined in.
/// </summary>
internal abstract void Shade(in Matrix3x2 toUser, int y, int x0, Span<Vector4> output);
/// <summary>A colour as the shading works with it.</summary>
internal static Vector4 ToVector(Color color) => new(color.R, color.G, color.B, color.A / 255f);
}
/// <summary>One colour.</summary>
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<Vector4> output) => output.Fill(Value);
}
/// <summary>
/// A linear gradient from <see cref="Start"/> to <see cref="End"/>: 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.
/// </summary>
public sealed class LinearGradientBrush : Brush
{
private readonly Vector4[] _colors;
private readonly float[] _positions;
/// <param name="start">Where the first colour is, in the coordinates the shape is drawn in.</param>
/// <param name="end">Where the last colour is.</param>
/// <param name="colors">Two or more colours.</param>
/// <param name="positions">Where each colour sits between start (0) and end (1), increasing; evenly spaced when null.</param>
public LinearGradientBrush(Vector2 start, Vector2 end, IReadOnlyList<Color> colors, IReadOnlyList<float>? 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<Vector4> 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);
}
}
+549
View File
@@ -0,0 +1,549 @@
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Drawing;
/// <summary>How the ends of a stroked line look.</summary>
public enum LineCap
{
/// <summary>The line stops at its end points.</summary>
Butt,
/// <summary>A half circle around each end point.</summary>
Round,
/// <summary>The line goes on for half its width beyond each end point.</summary>
Square,
}
/// <summary>
/// Draws anti-aliased shapes on an <see cref="RgbaImage"/>: 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 <see cref="Transform"/>, which <see cref="Translate"/>,
/// <see cref="Scale"/> and <see cref="Rotate"/> change and <see cref="Save"/> / <see cref="Restore"/> keep.
/// Written in house (no graphics library): the coverage of every pixel is the exact area of the shape inside it.
/// </summary>
public sealed class Canvas : IDisposable
{
private readonly RgbaImage _target;
private readonly Stack<Matrix2D> _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;
/// <summary>The image drawn on.</summary>
public RgbaImage Target => _target;
/// <summary>From the coordinates of the shapes to the pixels of the canvas.</summary>
public Matrix2D Transform { get; set; } = Matrix2D.Identity;
/// <summary>Remembers the transform, for <see cref="Restore"/>.</summary>
public void Save() => _saved.Push(Transform);
/// <summary>Back to the transform of the last <see cref="Save"/>.</summary>
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);
/// <summary>Rotates the shapes drawn next by <paramref name="degrees"/> around the origin, clockwise on screen.</summary>
public void Rotate(float degrees) => Transform = Transform.Then(Matrix2D.Rotation(degrees));
/// <summary>Every pixel set to <paramref name="color"/>, ignoring what was there.</summary>
public void Clear(Color color)
{
var pixels = _target.Pixels;
Span<byte> 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));
/// <summary>Fills the shape <paramref name="path"/> describes (non-zero winding).</summary>
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));
/// <summary>Fills a rectangle; without rotation the coverage of its border pixels is computed directly.</summary>
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);
/// <summary>The outline of a rectangle, <paramref name="lineWidth"/> wide and centred on its sides, square corners.</summary>
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);
}
/// <summary>A ring: the outline of an ellipse, <paramref name="lineWidth"/> wide and centred on it.</summary>
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);
/// <summary>A straight line <paramref name="lineWidth"/> wide.</summary>
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);
/// <summary>
/// The contours of <paramref name="path"/> drawn as lines <paramref name="lineWidth"/> wide, with round joins
/// and the given caps on open contours.
/// </summary>
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<Vector2[]>();
foreach (var contour in path.Flatten(Transform))
{
StrokePieces(contour, half, cap, pieces);
}
FillPolygons(pieces, new SolidBrush(color));
}
/// <summary>
/// A disc whose edge is blurred by a Gaussian of <paramref name="sigma"/> (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.
/// </summary>
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);
}
}
}
}
/// <summary>Composites one colour over one pixel, without anti-aliasing (canvas pixels, the transform ignored).</summary>
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);
}
/// <summary>
/// Draws <paramref name="image"/> 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.
/// </summary>
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<Polyline> contours, Brush brush)
{
var polygons = new List<Vector2[]>(contours.Count);
foreach (var contour in contours)
{
if (contour.Points.Length >= 3)
{
polygons.Add(contour.Points);
}
}
FillPolygons(polygons, brush);
}
private void FillPolygons(List<Vector2[]> 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<float>.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<float>.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<float>.Shared.Rent(width);
var coverage = ArrayPool<float>.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<float>.Shared.Return(columns);
ArrayPool<float>.Shared.Return(coverage);
}
}
private void BlendRow(int y, int left, ReadOnlySpan<float> 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<Vector4>.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<Vector4>.Shared.Return(colors);
}
}
/// <summary>Source over, straight alpha: <paramref name="alpha"/> is the colour's alpha times the coverage.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void BlendPixel(Span<byte> 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);
}
/// <summary>The pieces of a stroke: a quadrilateral per segment, a disc per join, the caps; all turning the same way.</summary>
private static void StrokePieces(Polyline contour, float half, LineCap cap, List<Vector2[]> 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);
}
/// <summary>The polygon turning clockwise on screen (positive signed area with y downwards), reversed if needed.</summary>
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;
}
/// <summary>The complementary error function, |error| &lt; 1.5e-7 (Abramowitz and Stegun 7.1.26).</summary>
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;
}
}
+27
View File
@@ -0,0 +1,27 @@
namespace Febe.Core.Drawing;
/// <summary>A colour of the drawing code: 8-bit red, green, blue and alpha, not premultiplied.</summary>
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);
/// <summary>An opaque colour from 0xRRGGBB.</summary>
public static Color FromRgb(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
/// <summary>The same colour with another alpha.</summary>
public Color WithAlpha(byte alpha) => this with { A = alpha };
/// <summary>
/// The colour <paramref name="t"/> of the way from this one to <paramref name="other"/> (0 this, 1 the other),
/// truncated to whole levels; the alpha of this colour.
/// </summary>
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);
}
+237
View File
@@ -0,0 +1,237 @@
using System.Buffers;
using System.Numerics;
namespace Febe.Core.Drawing;
/// <summary>
/// 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.
/// </summary>
internal sealed class CoverageRasterizer : IDisposable
{
private float[] _cells = [];
private int _stride;
/// <summary>Left column of the window in the canvas.</summary>
public int Left { get; private set; }
/// <summary>Top row of the window in the canvas.</summary>
public int Top { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
/// <summary>Starts a new shape in the window (<paramref name="left"/>, <paramref name="top"/>, width × height).</summary>
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<float>.Shared.Return(_cells);
}
_cells = ArrayPool<float>.Shared.Rent(length);
}
_cells.AsSpan(0, length).Clear();
}
/// <summary>Adds the edges of a closed polygon (canvas pixels; the last point joins the first).</summary>
public void AddPolygon(ReadOnlySpan<Vector2> points)
{
for (var i = 0; i < points.Length; i++)
{
AddEdge(points[i], points[(i + 1) % points.Length]);
}
}
/// <summary>Adds one edge, in canvas pixels.</summary>
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<float> cuts = stackalloc float[4];
var count = 0;
cuts[count++] = 0;
foreach (var border in (ReadOnlySpan<float>)[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);
}
}
}
/// <summary>The coverage of row <paramref name="y"/> of the window (0-1 for each of its columns).</summary>
public void Coverage(int y, Span<float> 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<float>.Shared.Return(_cells);
_cells = [];
}
}
/// <summary>One edge with 0 ≤ x ≤ Width, the rows outside the window ignored.</summary>
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;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
using System.Numerics;
namespace Febe.Core.Drawing;
/// <summary>
/// An affine transform of the plane: x' = M11·x + M21·y + M31, y' = M12·x + M22·y + M32 (the layout of
/// <see cref="Matrix3x2"/>, which does the arithmetic). Transforms compose as with a canvas: the last one applied
/// to the canvas acts first on the shapes drawn.
/// </summary>
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));
/// <summary>A rotation by <paramref name="degrees"/> around the origin, clockwise on screen (y grows downwards).</summary>
public static Matrix2D Rotation(float degrees) => new(Matrix3x2.CreateRotation(degrees * MathF.PI / 180f));
/// <summary>The transform that applies <paramref name="inner"/> first and then this one.</summary>
public Matrix2D Then(Matrix2D inner) => new(inner.Value * Value);
public Vector2 Apply(Vector2 point) => Vector2.Transform(point, Value);
/// <summary>How much the transform enlarges lengths, on average (the square root of the area scale).</summary>
public float LengthScale => MathF.Sqrt(MathF.Abs(Value.GetDeterminant()));
}
+275
View File
@@ -0,0 +1,275 @@
using System.Numerics;
namespace Febe.Core.Drawing;
/// <summary>
/// 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.
/// </summary>
public sealed class PathBuilder
{
private readonly List<Command> _commands = [];
private enum Kind
{
Move,
Line,
Quad,
Cubic,
Arc,
Close,
}
/// <summary>Whether nothing was added.</summary>
public bool IsEmpty => _commands.Count == 0;
/// <summary>Starts a new contour at (<paramref name="x"/>, <paramref name="y"/>).</summary>
public PathBuilder MoveTo(float x, float y)
{
_commands.Add(new Command(Kind.Move, new Vector2(x, y)));
return this;
}
/// <summary>A straight line to (<paramref name="x"/>, <paramref name="y"/>).</summary>
public PathBuilder LineTo(float x, float y)
{
_commands.Add(new Command(Kind.Line, new Vector2(x, y)));
return this;
}
/// <summary>A quadratic Bézier curve through the control point (cx, cy) to (x, y).</summary>
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;
}
/// <summary>A cubic Bézier curve through the control points (c1x, c1y) and (c2x, c2y) to (x, y).</summary>
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;
}
/// <summary>
/// A new contour along the ellipse inscribed in the rectangle (<paramref name="left"/>, <paramref name="top"/>)–
/// (<paramref name="right"/>, <paramref name="bottom"/>), from <paramref name="startDegrees"/> for
/// <paramref name="sweepDegrees"/> (negative: the other way round).
/// </summary>
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;
}
/// <summary>Closes the current contour with a straight line back to its start.</summary>
public PathBuilder Close()
{
_commands.Add(new Command(Kind.Close, default));
return this;
}
/// <summary>A closed ellipse centred on (cx, cy), clockwise on screen (or the other way round).</summary>
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();
}
/// <summary>A closed circle.</summary>
public PathBuilder AddCircle(float cx, float cy, float r, bool clockwise = true) => AddEllipse(cx, cy, r, r, clockwise);
/// <summary>A closed rectangle, clockwise on screen (or the other way round).</summary>
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();
}
/// <summary>A closed rectangle with corners rounded to quarter circles of <paramref name="radius"/>.</summary>
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();
}
/// <summary>A closed polygon through <paramref name="points"/> (x0, y0, x1, y1, ...).</summary>
public PathBuilder AddPolygon(ReadOnlySpan<float> 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();
}
/// <summary>
/// The contours as polylines in canvas pixels, the curves divided finely enough that no chord strays more than
/// <paramref name="tolerance"/> 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.
/// </summary>
internal List<Polyline> Flatten(Matrix2D transform, float tolerance = 0.01f)
{
var result = new List<Polyline>();
var scale = Math.Max(transform.LengthScale, 1e-6f);
List<Vector2>? 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;
}
/// <summary>An arc that continues the current contour (used by the rounded rectangle).</summary>
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);
}
/// <summary>Chords of an arc of radius <paramref name="radiusPixels"/>, each with a sagitta of at most the tolerance.</summary>
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; }
}
}
/// <summary>A flattened contour in canvas pixels.</summary>
internal readonly record struct Polyline(Vector2[] Points, bool Closed);
-3
View File
@@ -1,9 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Dominio e logica: motore, Governatore, interruttore, ricette, lettori, libreria, importazione.
Nessun riferimento a interfaccia o piattaforma: Data e Browser implementano le interfacce definite qui. -->
<ItemGroup>
<PackageReference Include="SkiaSharp" />
</ItemGroup>
<ItemGroup>
<!-- File di configurazione per sito (specifica §6.3, §7.6): una copia incorporata come valore predefinito
e una copia accanto all'eseguibile, in config/, modificabile senza ricompilare. -->
+18 -3
View File
@@ -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);
}
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC).</summary>
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);
}
}
/// <summary>The same for a photo too large to keep in memory, opened twice.</summary>
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> 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
}
}
+4 -18
View File
@@ -1,34 +1,20 @@
using Febe.Core.Library;
using SkiaSharp;
namespace Febe.Core.Import;
/// <summary>In-memory previews of source photos for the comparison panel (nothing is written to disk).</summary>
internal static class ImportPreview
{
private const int JpegQuality = 82;
/// <summary>A JPEG of the image, upright, at most <paramref name="longSide"/> pixels; null when it cannot be decoded.</summary>
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);
}
}
+1 -1
View File
@@ -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.
+74 -81
View File
@@ -1,10 +1,11 @@
using SkiaSharp;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Library;
/// <summary>
/// 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 (<see cref="ImageDecoder"/>: 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.
/// </summary>
internal static class ImageDecoding
{
@@ -14,118 +15,110 @@ internal static class ImageDecoding
/// </summary>
public const long MaxDecodedPixels = 100_000_000;
/// <summary>Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it).</summary>
public const long MaxFileBytes = 512L * 1024 * 1024;
private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels };
/// <summary>
/// Decodes an image upright, as premultiplied RGBA. When <paramref name="minLongSide"/> 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 <paramref name="minLongSide"/> 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).
/// </summary>
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;
}
/// <summary>Like <see cref="DecodeUpright(Stream, int?)"/>, from bytes already in memory.</summary>
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> 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);
}
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
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;
}
/// <summary>Like <see cref="ReadSize(Stream)"/>, from bytes already in memory.</summary>
public static (int Width, int Height)? ReadSize(ReadOnlyMemory<byte> 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();
}
}
+26 -42
View File
@@ -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;
/// <summary>A JPEG is decoded reduced, but never below this long side.</summary>
private const int MinDecodedSide = 256;
private static readonly double[,] Cosines = BuildCosines();
/// <summary>Hamming distance between two hashes (0–64).</summary>
@@ -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);
}
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
@@ -61,17 +64,11 @@ public static class PerceptualHash
return Compute(stream);
}
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
internal static ulong Compute(SKBitmap bitmap)
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
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));
}
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
@@ -123,50 +120,37 @@ public static class PerceptualHash
return hash;
}
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
private static double[] Luminance(SKBitmap bitmap)
/// <summary>
/// The grey levels (0–255, over white: <see cref="ImageGray.LumaOverWhite"/>) of an image reduced to dw × dh by area
/// averaging, one source row at a time (memory: one row and dw × source height values).
/// </summary>
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;
}
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
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++)
+57 -62
View File
@@ -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)
/// <summary>
/// Decodes an image upright for a picture of <paramref name="longSide"/> 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.
/// </summary>
internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
/// <summary>
/// The image reduced to <paramref name="longSide"/> 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.
/// </summary>
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)
/// <summary>The JPEG of a thumbnail: quality <see cref="JpegQuality"/>, chroma 4:2:0.</summary>
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);
}
}
}