Files
Febe/src/Febe.Core/Codecs/Images/JpegDecoder.cs
T
Alby96andClaude Opus 5.5 d6a6a68496 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>
2026-11-18 16:02:03 +01:00

113 lines
6.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Reads JPEG files (ITU-T T.81): baseline and extended sequential DCT, progressive DCT (spectral selection and
/// successive approximation), lossless, each with Huffman or arithmetic coding, 8 and 12 bits (lossless 2-16), any
/// sampling factors, restart intervals and DNL. Grey, YCbCr (JFIF), RGB, and with an Adobe APP14 segment CMYK and
/// YCCK, all converted to straight RGBA8 (alpha 255). The IDCT is accurate (single precision), chroma is upsampled
/// with the triangular filter where the ratio is 2 and replicated otherwise. Metadata: EXIF (with its orientation,
/// reported and not applied), the ICC profile from its APP2 chunks, XMP, comments.
/// </summary>
/// <remarks>
/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have; a missing EOI after complete
/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
/// with <see cref="ImageFormatNotSupportedException"/>.
/// </remarks>
public static class JpegDecoder
{
/// <summary>Whether the bytes start like a JPEG file (SOI and the start of a marker).</summary>
public static bool IsJpeg(ReadOnlySpan<byte> data) => data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF;
/// <summary>Size and metadata of a JPEG, without decoding the pixels.</summary>
/// <exception cref="ImageDecodeException">The file is damaged or not a JPEG.</exception>
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Identify, readMetadata: true);
file.Run();
return file.ToInfo();
}
/// <summary>Decodes a JPEG to straight RGBA8.</summary>
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a JPEG.</exception>
/// <exception cref="ImageFormatNotSupportedException">The file uses the hierarchical process.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
{
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: false);
file.Run();
return file.Render(pooled);
}
/// <summary>Decodes a JPEG to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
{
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true);
file.Run();
var image = file.Render(pooled);
info = file.ToInfo();
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).
/// </summary>
internal static JpegCoefficients DecodeCoefficients(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Coefficients, readMetadata: false);
file.Run();
return file.ToCoefficients();
}
}
/// <summary>The coefficients of one component, natural order inside each block, blocks row after row.</summary>
/// <param name="Id">Component identifier.</param>
/// <param name="H">Horizontal sampling factor.</param>
/// <param name="V">Vertical sampling factor.</param>
/// <param name="BlocksWide">Blocks that cover the component's samples horizontally.</param>
/// <param name="BlocksHigh">Blocks that cover the component's samples vertically.</param>
/// <param name="Stride">Blocks per row in <paramref name="Coefficients"/> (the MCU grid, at least <paramref name="BlocksWide"/>).</param>
/// <param name="Quantization">The quantization table the component used, natural order.</param>
/// <param name="Coefficients">64 coefficients per block.</param>
internal sealed record JpegComponentCoefficients(int Id, int H, int V, int BlocksWide, int BlocksHigh, int Stride, ushort[] Quantization, short[] Coefficients)
{
/// <summary>The DQT table the component refers to.</summary>
public int QuantizationTable { get; init; }
/// <summary>Rows of blocks in <see cref="Coefficients"/>.</summary>
public int StoredRows => Coefficients.Length / 64 / Stride;
/// <summary>The 64 coefficients of block (<paramref name="x"/>, <paramref name="y"/>).</summary>
public ReadOnlySpan<short> Block(int x, int y) => Coefficients.AsSpan(((y * Stride) + x) * 64, 64);
}
/// <summary>What <see cref="JpegDecoder.DecodeCoefficients"/> returns.</summary>
internal sealed record JpegCoefficients(
int FrameMarker,
int Precision,
int Width,
int Height,
int RestartInterval,
int AdobeTransform,
bool Jfif,
int ScanCount,
IReadOnlyList<JpegComponentCoefficients> Components);