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;
}
}
}