using ImageMagick; using StbImageSharp; namespace Messenger.Api.Jobs; public sealed record ImageVariant(string Name, string ContentType, byte[] Bytes, int Width, int Height) { public static ImageVariant[] CreateAll(Stream original, string mime, long maxPixels, int version) { if (version is not (1 or 2) || mime is not ("image/png" or "image/jpeg")) throw new InvalidDataException("Unsupported image or pipeline version"); original.Position = 0; var header = ImageInfo.FromStream(original); if (header is null || header.Value.Width <= 0 || header.Value.Height <= 0 || (long)header.Value.Width * header.Value.Height > maxPixels) throw new InvalidDataException("Invalid image dimensions"); original.Position = 0; var read = new MagickReadSettings { Format = mime == "image/png" ? MagickFormat.Png : MagickFormat.Jpeg, FrameCount = 1 }; using var image = new MagickImage(original, read); if (image.Width != header.Value.Width || image.Height != header.Value.Height) throw new InvalidDataException("Image dimensions changed during decode"); image.AutoOrient(); image.Strip(); using var thumbnail = image.Clone(); Fit(thumbnail, 256); using var crop = image.Clone(); var side = Math.Min(crop.Width, crop.Height); crop.Crop(side, side, Gravity.Center); crop.ResetPage(); crop.Resize(128, 128); Fit(image, 1280); image.Quality = version == 1 ? 78u : 86u; return [EncodeJpeg(thumbnail, "thumbnail", version == 1 ? 85u : 92u), EncodeJpeg(crop, "crop", 85), new ImageVariant("optimized", "image/webp", image.ToByteArray(MagickFormat.WebP), (int)image.Width, (int)image.Height)]; } private static void Fit(IMagickImage image, uint limit) { var longest = Math.Max(image.Width, image.Height); if (longest <= limit) return; var width = (uint)Math.Max(1L, image.Width * (long)limit / longest); var height = (uint)Math.Max(1L, image.Height * (long)limit / longest); image.Resize(new MagickGeometry(width, height) { IgnoreAspectRatio = true }); } private static ImageVariant EncodeJpeg(IMagickImage image, string name, uint quality) { image.BackgroundColor = MagickColors.White; image.Alpha(AlphaAction.Remove); image.Quality = quality; return new(name, "image/jpeg", image.ToByteArray(MagickFormat.Jpeg), (int)image.Width, (int)image.Height); } }