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

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