| | | 1 | | using Anichron.Worker.Settings; |
| | | 2 | | using Blurhash.ImageSharp; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using SixLabors.ImageSharp; |
| | | 5 | | using SixLabors.ImageSharp.Formats.Jpeg; |
| | | 6 | | using SixLabors.ImageSharp.PixelFormats; |
| | | 7 | | using SixLabors.ImageSharp.Processing; |
| | | 8 | | |
| | | 9 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 10 | | |
| | | 11 | | internal interface IImageProcessor |
| | | 12 | | { |
| | | 13 | | Task<byte[]> CreateThumbnailAsync(Image<Rgba32> image, CancellationToken ct); |
| | | 14 | | Task<byte[]> CreateFullPreviewAsync(Image<Rgba32> image, CancellationToken ct); |
| | | 15 | | Task<string> ComputeBlurhashAsync(Image<Rgba32> image, CancellationToken ct); |
| | | 16 | | } |
| | | 17 | | |
| | 0 | 18 | | internal sealed class ImageSharpProcessor(IOptions<WorkerSettings> options) : IImageProcessor |
| | | 19 | | { |
| | 0 | 20 | | private readonly WorkerSettings settings = options.Value; |
| | | 21 | | |
| | | 22 | | public async Task<byte[]> CreateThumbnailAsync(Image<Rgba32> image, CancellationToken ct) |
| | 0 | 23 | | { |
| | | 24 | | image.Mutate(x => x.Resize(new ResizeOptions |
| | | 25 | | { |
| | | 26 | | Size = new Size(settings.ThumbnailMaxWidth, 0), |
| | | 27 | | Mode = ResizeMode.Max, |
| | | 28 | | })); |
| | | 29 | | |
| | 0 | 30 | | await using var ms = new MemoryStream(); |
| | 0 | 31 | | await image.SaveAsJpegAsync(ms, new JpegEncoder { Quality = settings.ThumbnailJpegQuality }, ct); |
| | 0 | 32 | | return ms.ToArray(); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | public async Task<byte[]> CreateFullPreviewAsync(Image<Rgba32> image, CancellationToken ct) |
| | 0 | 36 | | { |
| | 0 | 37 | | if (image.Width > settings.PreviewMaxWidth) |
| | 0 | 38 | | { |
| | | 39 | | image.Mutate(x => x.Resize(new ResizeOptions |
| | | 40 | | { |
| | | 41 | | Size = new Size(settings.PreviewMaxWidth, 0), |
| | | 42 | | Mode = ResizeMode.Max, |
| | | 43 | | })); |
| | 0 | 44 | | } |
| | | 45 | | |
| | 0 | 46 | | await using var ms = new MemoryStream(); |
| | 0 | 47 | | await image.SaveAsJpegAsync(ms, new JpegEncoder { Quality = settings.PreviewJpegQuality }, ct); |
| | 0 | 48 | | return ms.ToArray(); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | public Task<string> ComputeBlurhashAsync(Image<Rgba32> image, CancellationToken ct) |
| | 0 | 52 | | { |
| | 0 | 53 | | image.Mutate(x => x.Resize(new ResizeOptions |
| | 0 | 54 | | { |
| | 0 | 55 | | Size = new Size(settings.BlurhashSampleWidth, 0), |
| | 0 | 56 | | Mode = ResizeMode.Max, |
| | 0 | 57 | | })); |
| | | 58 | | |
| | | 59 | | // Blurhasher.Encode is CPU-bound and synchronous; no overload accepts a CancellationToken. |
| | 0 | 60 | | return Task.FromResult(Blurhasher.Encode(image, 4, 3)); |
| | 0 | 61 | | } |
| | | 62 | | } |