| | | 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 | | |
| | | 8 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 9 | | |
| | | 10 | | internal interface IImageProcessor |
| | | 11 | | { |
| | | 12 | | Task<byte[]> EncodeThumbnailAsync(Image<Rgb24> image, CancellationToken ct); |
| | | 13 | | Task<byte[]> EncodeFullPreviewAsync(Image<Rgb24> image, CancellationToken ct); |
| | | 14 | | Task<string> ComputeBlurhashAsync(Image<Rgb24> image, CancellationToken ct); |
| | | 15 | | } |
| | | 16 | | |
| | 43 | 17 | | internal sealed class ImageSharpProcessor(IOptions<WorkerSettings> options) : IImageProcessor |
| | | 18 | | { |
| | 43 | 19 | | private readonly WorkerSettings settings = options.Value; |
| | | 20 | | |
| | | 21 | | public Task<byte[]> EncodeThumbnailAsync(Image<Rgb24> image, CancellationToken ct) |
| | 37 | 22 | | => EncodeJpegAsync(image, settings.ThumbnailJpegQuality, ct); |
| | | 23 | | |
| | | 24 | | public Task<byte[]> EncodeFullPreviewAsync(Image<Rgb24> image, CancellationToken ct) |
| | 37 | 25 | | => EncodeJpegAsync(image, settings.PreviewJpegQuality, ct); |
| | | 26 | | |
| | | 27 | | // Blurhasher.Encode is CPU-bound and synchronous; no overload accepts a CancellationToken. |
| | | 28 | | public Task<string> ComputeBlurhashAsync(Image<Rgb24> image, CancellationToken ct) |
| | 37 | 29 | | => Task.FromResult(Blurhasher.Encode(image, 4, 3)); |
| | | 30 | | |
| | | 31 | | private static async Task<byte[]> EncodeJpegAsync(Image<Rgb24> image, int quality, CancellationToken ct) |
| | 74 | 32 | | { |
| | 74 | 33 | | await using var ms = new MemoryStream(); |
| | 74 | 34 | | await image.SaveAsJpegAsync(ms, new JpegEncoder { Quality = quality }, ct); |
| | 74 | 35 | | return ms.ToArray(); |
| | 74 | 36 | | } |
| | | 37 | | } |