using SkiaSharp;
namespace Febe.Core.Library;
///
/// 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.
///
internal static class ImageDecoding
{
///
/// Images larger than this (after the codec's own reduction) are not decoded: a 100-megapixel PNG would need 400 MB.
/// Such files simply get no thumbnail and no perceptual hash.
///
public const long MaxDecodedPixels = 100_000_000;
///
/// Decodes an image upright, as premultiplied RGBA. When 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.
///
public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null)
{
ArgumentNullException.ThrowIfNull(stream);
using var data = SKData.Create(stream);
if (data is null || data.IsEmpty)
{
return null;
}
using var codec = SKCodec.Create(data);
if (codec is null)
{
return null;
}
var size = ChooseDecodeSize(codec, minLongSide);
if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0)
{
return null;
}
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);
}
/// Dimensions of an image as displayed (orientation applied), without decoding the pixels.
public static (int Width, int Height)? ReadSize(Stream stream)
{
ArgumentNullException.ThrowIfNull(stream);
using var codec = SKCodec.Create(stream);
if (codec is null)
{
return null;
}
var (w, h) = (codec.Info.Width, codec.Info.Height);
return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
}
private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
{
var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min)
{
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)
{
break;
}
best = scaled;
}
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)
{
return source;
}
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;
}
}