using System.Text; namespace Febe.Core.Codecs.Images; /// Options of . public sealed record ImageConversionOptions { /// The options used when a caller passes none. public static ImageConversionOptions Default { get; } = new(); /// Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026). public int JpegQuality { get; init; } = 92; /// Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible. public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444; /// What transparent areas become in a JPEG target, which has no alpha. public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White; /// Limits of the decoding of the source. public ImageLimits Limits { get; init; } = ImageLimits.Default; } /// What made. /// The converted file. /// The format of the source. /// The format written. /// Width as stored (the orientation is not applied: the tag is copied). /// Height as stored. /// /// Whether pixels may differ from the source's: a JPEG target, or a source with more than 8 bits per sample (the /// decoders keep 8). /// /// The metadata written. /// What of the source's metadata the target could not take, in Italian, for the interface. /// /// The same as note codes (tappa E3, ), once each, in a fixed order: what the export /// and the library conversion record. /// public sealed record ImageConversionResult( byte[] Data, ImageFormat Source, ImageFormat Target, int Width, int Height, bool Lossy, ImageMetadata Metadata, IReadOnlyList NotCarried, IReadOnlyList Losses); /// What a conversion does with a source (tappa E3, decisions D5 and D6). public enum ImageConversionAction { /// The source is already in the target format: it is copied byte for byte, without a note. CopyAsIs, /// The source is decoded and written in the target format. Convert, /// The source cannot be converted without losing what matters: it is copied as it is, with a note. CopyOriginal, } /// The outcome of . /// What to do. /// The format of the source by its bytes; null when it is not recognised. /// For , why (AsIsHeif, AsIsAnimated...). public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode); /// The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3). public static class ImageConversionLosses { public const string AsIsHeif = "AsIsHeif"; public const string AsIsAvif = "AsIsAvif"; public const string AsIsRaw = "AsIsRaw"; public const string AsIsAnimated = "AsIsAnimated"; public const string AsIsNotDecodable = "AsIsNotDecodable"; public const string AsIsDeepColor = "AsIsDeepColor"; public const string AsIsCmyk = "AsIsCmyk"; public const string AsIsTooLarge = "AsIsTooLarge"; public const string LostTexts = "LostTexts"; public const string LostColorChunks = "LostColorChunks"; public const string LostIcc = "LostIcc"; public const string LostIccTooLarge = "LostIccTooLarge"; public const string LostExifTooLarge = "LostExifTooLarge"; public const string LostXmpTooLarge = "LostXmpTooLarge"; public const string LostExtendedXmp = "LostExtendedXmp"; public const string LostExifUnreadable = "LostExifUnreadable"; public const string LostIptc = "LostIptc"; public const string LostOtherSegments = "LostOtherSegments"; public const string LostCommentTooLarge = "LostCommentTooLarge"; public const string TransparencyWhite = "TransparencyWhite"; /// The order in which the codes are listed, so that the same source always gives the same note. internal static readonly string[] Order = [ TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp, LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments, ]; } /// /// 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 without further loss, /// JPEG at the quality of the options. The pixels written are always 8-bit RGB(A): a source with more bits per /// sample (16-bit PNG, 12-bit or lossless JPEG) loses that precision, which the result reports as lossy. The EXIF /// block (dates, camera, the orientation tag) and the XMP packet are copied as they are, the ICC profile only when it /// describes RGB data (a CMYK or grey profile would no longer fit the RGB pixels); 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. The PNG colour chunks (gAMA, cHRM, sRGB) are not written. Whatever /// cannot be carried is listed in . Animations keep their first frame /// only, and say so. /// public static class ImageConverter { /// The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB). public const long MaxSourceBytes = 512L * 1024 * 1024; /// The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory). public const long MaxWebPPixels = 40_000_000; /// The formats a conversion can write. public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP; /// /// What a conversion of to does, from its bytes and its header /// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF /// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures /// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file. /// /// The target is not JPEG, PNG or WebP. public static ImageConversionCheck Check(ReadOnlyMemory data, ImageFormat target, ImageConversionOptions? options = null) { if (!CanWrite(target)) { throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target)); } options ??= ImageConversionOptions.Default; var source = ImageFormatSniffer.Detect(data.Span); if (source == target) { return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null); } string? asIs = source switch { ImageFormat.Heif => ImageConversionLosses.AsIsHeif, ImageFormat.Avif => ImageConversionLosses.AsIsAvif, ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...) ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable, _ => null, }; if (asIs is null && data.Length > MaxSourceBytes) { asIs = ImageConversionLosses.AsIsTooLarge; } if (asIs is null) { asIs = IdentifyOutcome(data, target, options.Limits); } return asIs is null ? new ImageConversionCheck(ImageConversionAction.Convert, source, null) : new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs); } private static string? IdentifyOutcome(ReadOnlyMemory data, ImageFormat target, ImageLimits limits) { ImageInfo info; try { info = ImageDecoder.Identify(data, limits); } catch (ImageLimitException) { return ImageConversionLosses.AsIsTooLarge; } catch (ImageDecodeException) { return ImageConversionLosses.AsIsNotDecodable; } if (info.IsAnimated) { return ImageConversionLosses.AsIsAnimated; } if (target != ImageFormat.Jpeg && info.IsCmyk) { return ImageConversionLosses.AsIsCmyk; } if (target != ImageFormat.Jpeg && info.BitsPerSample > 8) { return ImageConversionLosses.AsIsDeepColor; } var pixels = (long)info.Width * info.Height; var tooLarge = target == ImageFormat.WebP ? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension : pixels > ImageLimits.Default.MaxPixels; // What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder // would refuse is too large for the conversion, never «not readable» (§4.10). tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes; return tooLarge ? ImageConversionLosses.AsIsTooLarge : null; } /// Converts (any format reads) to . /// The target is not JPEG, PNG or WebP. /// The source is damaged, too large or in a format Febe does not read. public static ImageConversionResult Convert(ReadOnlyMemory source, ImageFormat target, ImageConversionOptions? options = null) { if (!CanWrite(target)) { throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target)); } options ??= ImageConversionOptions.Default; using var image = ImageDecoder.Decode(source, out var info, options.Limits, pooled: true); var notCarried = new List(); if (info.FrameCount > 1) { notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}"); } var lossy = target == ImageFormat.Jpeg; if (info.BitsPerSample > 8) { notCarried.Add($"la profondità di {info.BitsPerSample} bit per campione (i pixel sono scritti a 8 bit)"); lossy = true; } var losses = new HashSet(StringComparer.Ordinal); var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written); return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses)); } /// /// Writes (straight RGBA) as with what of /// the target can carry (none when null: the frames of tappa E3). A transparent image /// to JPEG is first flattened over the background of the options, on a copy: is never /// changed. /// /// The target is not JPEG, PNG or WebP, or a WebP side is over 16384. public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null) { ArgumentNullException.ThrowIfNull(image); if (!CanWrite(target)) { throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target)); } options ??= ImageConversionOptions.Default; if (target == ImageFormat.Jpeg && !image.IsOpaque()) { using var copy = new RgbaImage(image.Width, image.Height, image.ToArray()); return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet(StringComparer.Ordinal), out _); } return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet(StringComparer.Ordinal), out _); } /// The codes of in the order of . private static string[] Ordered(HashSet losses) => [.. ImageConversionLosses.Order.Where(losses.Contains)]; /// Encodes; flattens in place for a JPEG target that is not opaque. private static byte[] EncodeCore( RgbaImage image, ImageFormat target, ImageMetadata metadata, ImageConversionOptions options, List notCarried, HashSet losses, out ImageMetadata written) { var exif = metadata.Exif; if (exif is not null && !ExifOrientation.IsTiff(exif)) { notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)"); losses.Add(ImageConversionLosses.LostExifUnreadable); exif = OrientationOnly(metadata); } var icc = metadata.IccProfile; var iccName = metadata.IccProfileName; if (icc is not null && IccColorSpace(icc) != "RGB ") { notCarried.Add(IccColorSpace(icc) switch { "CMYK" => "il profilo colore CMYK (i pixel sono stati convertiti in RGB)", "GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)", _ => "il profilo colore (non descrive pixel RGB)", }); losses.Add(ImageConversionLosses.LostIcc); icc = null; iccName = null; } foreach (var chunk in metadata.ColorChunks) { notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)"); losses.Add(ImageConversionLosses.LostColorChunks); } foreach (var block in metadata.Unread) { switch (block) { case "APP13": notCarried.Add("i dati IPTC (segmento APP13)"); losses.Add(ImageConversionLosses.LostIptc); break; case "ExtendedXmp": notCarried.Add("l'XMP esteso"); losses.Add(ImageConversionLosses.LostExtendedXmp); break; default: notCarried.Add($"il blocco {block}"); losses.Add(ImageConversionLosses.LostOtherSegments); break; } } var xmp = metadata.Xmp; var texts = metadata.Texts; IReadOnlyList writtenTexts = texts; byte[] data; switch (target) { case ImageFormat.Png: { var pngTexts = PngTexts(texts, notCarried, losses); writtenTexts = pngTexts; data = PngEncoder.Encode(image, new PngEncoderOptions { Exif = exif, IccProfile = icc, IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName, Xmp = xmp, Texts = pngTexts, }); 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)"); losses.Add(ImageConversionLosses.LostTexts); } writtenTexts = []; 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)"); losses.Add(ImageConversionLosses.LostExifTooLarge); exif = OrientationOnly(metadata); } if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29) { notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)"); losses.Add(ImageConversionLosses.LostXmpTooLarge); xmp = null; } if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255) { notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)"); losses.Add(ImageConversionLosses.LostIccTooLarge); icc = null; iccName = null; } var comments = new List(); var kept = new List(); foreach (var text in texts) { var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}"; if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload) { notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)"); losses.Add(ImageConversionLosses.LostCommentTooLarge); continue; } comments.Add(comment); kept.Add(text); } writtenTexts = kept; if (!image.IsOpaque()) { ImageBackground.Flatten(image, options.JpegBackground); notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)"); losses.Add(ImageConversionLosses.TransparencyWhite); } data = JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = options.JpegQuality, Subsampling = options.JpegSubsampling, Exif = exif, IccProfile = icc, Xmp = xmp, Comments = comments, }); break; } } written = new ImageMetadata { Exif = exif, Orientation = exif is null ? 1 : metadata.Orientation, IccProfile = icc, IccProfileName = icc is null ? null : iccName, Xmp = xmp, Texts = writtenTexts, }; return data; } /// /// In place of an EXIF block left behind, the smallest one that keeps its orientation (in the source's byte order), /// or null when the orientation is 1: the pixels are never turned (§4.10), so without the tag the picture would /// show turned. The loss stays in the notes. /// private static byte[]? OrientationOnly(ImageMetadata metadata) => metadata.Orientation is > 1 and <= 8 ? ExifOrientation.Minimal(metadata.Orientation, metadata.Exif is not { Length: > 0 } e || e[0] != (byte)'M') : null; /// The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null. internal static string? IccColorSpace(ReadOnlySpan profile) { if (profile.Length < 20) { return null; } Span name = stackalloc char[4]; for (var i = 0; i < 4; i++) { var b = profile[16 + i]; if (b is < 32 or > 126) { return null; } name[i] = (char)b; } return new string(name); } /// Bytes of payload in one JPEG marker segment (65535 less the two of the length). private const int JpegMaxSegmentPayload = 65533; /// Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters). private const int JpegIccChunk = 65519; private static string? ValidIccName(string? name) { if (string.IsNullOrEmpty(name) || name.Length > 79) { return null; } foreach (var c in name) { if (c < 32 || c > 255 || (c > 126 && c < 161)) { return null; } } return name.Trim().Length == name.Length ? name : null; } private static List PngTexts(IReadOnlyList texts, List notCarried, HashSet losses) { var result = new List(texts.Count); foreach (var text in texts) { var keyword = text.Keyword.Length == 0 ? "Comment" : text.Keyword; if (!PngEncoder.IsValidKeyword(keyword)) { notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)"); losses.Add(ImageConversionLosses.LostTexts); continue; } result.Add(text with { Keyword = keyword }); } return result; } } /// Composites an image over a plain colour. public static class ImageBackground { /// Every pixel of seen over , opaque, in place. public static void Flatten(RgbaImage image, Drawing.Color background) { ArgumentNullException.ThrowIfNull(image); var pixels = image.Pixels; for (var i = 0; i < pixels.Length; i += 4) { int a = pixels[i + 3]; if (a == 255) { continue; } var keep = 255 - a; pixels[i] = (byte)(((pixels[i] * a) + (background.R * keep) + 127) / 255); pixels[i + 1] = (byte)(((pixels[i + 1] * a) + (background.G * keep) + 127) / 255); pixels[i + 2] = (byte)(((pixels[i + 2] * a) + (background.B * keep) + 127) / 255); pixels[i + 3] = 255; } } }