namespace SlpModularCms.Core.Media; /// Decides which files to make from an image: per ratio the crop and the widths, per width the formats. Pure. public static class VariantPlanner { public const int WebPQuality = 80; public const int AvifQuality = 50; public const int JpegQuality = 82; /// The widths per ratio of the first version of the hero (never above the source: see ). public static IReadOnlyList DefaultWidths(Ratio ratio) => ratio.Name switch { "wide" => [640, 960, 1280, 1600, 2560], "tall" => [480, 640, 960, 1280], _ => [640, 960, 1280], }; /// /// For every ratio: the crop around the focus, then the widths that are not wider than the crop (an image is never /// scaled up); when the crop is narrower than the smallest wanted width, one variant at the crop width. Each width is /// planned in WebP, and in AVIF when contains it. WebP is required: without WebP the /// plan falls back to JPEG so a platform without a WebP encoder still publishes something. /// /// The ratio name of the full-frame preview (the whole picture, not cut around a point). public const string PreviewRatioName = "full"; /// The widest full-frame preview. public const int PreviewMaxWidth = 1280; /// /// The full-frame preview an administrator needs to choose the focus point: the WHOLE oriented picture at its own /// shape, scaled down to at most (never up). Not published to websites. /// public static VariantSpec Preview(int sourceWidth, int sourceHeight, IReadOnlySet outputs) { var width = Math.Min(PreviewMaxWidth, sourceWidth); var height = Math.Max(1, (int)Math.Round(width * (double)sourceHeight / sourceWidth)); var (format, quality) = outputs.Contains(ImageFormat.WebP) ? (ImageFormat.WebP, WebPQuality) : (ImageFormat.Jpeg, JpegQuality); return new VariantSpec(new Ratio(PreviewRatioName, sourceWidth, sourceHeight), width, height, format, quality, new CropRect(0, 0, sourceWidth, sourceHeight)); } public static IReadOnlyList Plan( int sourceWidth, int sourceHeight, IReadOnlyList ratios, IReadOnlySet outputs) { var formats = new List<(ImageFormat Format, int Quality)>(); if (outputs.Contains(ImageFormat.WebP)) { formats.Add((ImageFormat.WebP, WebPQuality)); } else { formats.Add((ImageFormat.Jpeg, JpegQuality)); } if (outputs.Contains(ImageFormat.Avif)) { formats.Add((ImageFormat.Avif, AvifQuality)); } var result = new List(); foreach (var plan in ratios) { var crop = FocusMath.CropFor(sourceWidth, sourceHeight, plan.Ratio, plan.Focus); var widths = plan.Widths.Where(w => w > 0 && w <= crop.Width).Distinct().OrderBy(w => w).ToList(); if (widths.Count == 0) { widths.Add(crop.Width); } foreach (var width in widths) { var height = Math.Max(1, (int)Math.Round(width * (double)plan.Ratio.Denominator / plan.Ratio.Numerator)); foreach (var (format, quality) in formats) { result.Add(new VariantSpec(plan.Ratio, width, height, format, quality, crop)); } } } return result; } }