| | | 1 | | using SixLabors.ImageSharp; |
| | | 2 | | using SixLabors.ImageSharp.PixelFormats; |
| | | 3 | | using SixLabors.ImageSharp.Processing; |
| | | 4 | | |
| | | 5 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 6 | | |
| | | 7 | | internal interface IUprightImageDecoder |
| | | 8 | | { |
| | | 9 | | Task<Image<Rgb24>> DecodeAsync(byte[] original, CancellationToken ct); |
| | | 10 | | } |
| | | 11 | | |
| | | 12 | | internal sealed class UprightImageDecoder(MagickHeifDecoder heif, ImageSharpUprightDecoder imageSharp) : IUprightImageDe |
| | | 13 | | { |
| | | 14 | | public Task<Image<Rgb24>> DecodeAsync(byte[] original, CancellationToken ct) |
| | | 15 | | { |
| | | 16 | | if (IsHeifStill(original)) |
| | | 17 | | { |
| | | 18 | | ImageCompleteness.EnsureHeif(original); |
| | | 19 | | return heif.DecodeAsync(original, ct); |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | if (original is [0xFF, 0xD8, ..]) |
| | | 23 | | ImageCompleteness.EnsureJpeg(original); |
| | | 24 | | return imageSharp.DecodeAsync(original, ct); |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | private static bool IsHeifStill(byte[] original) |
| | | 28 | | => original is [_, _, _, _, (byte)'f', (byte)'t', (byte)'y', (byte)'p', .. var brand] |
| | | 29 | | && brand is [(byte)'h', (byte)'e', (byte)'i', (byte)'c', ..] |
| | | 30 | | or [(byte)'h', (byte)'e', (byte)'i', (byte)'x', ..] |
| | | 31 | | or [(byte)'m', (byte)'i', (byte)'f', (byte)'1', ..]; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | internal sealed class ImageSharpUprightDecoder : IUprightImageDecoder |
| | | 35 | | { |
| | | 36 | | public async Task<Image<Rgb24>> DecodeAsync(byte[] original, CancellationToken ct) |
| | 54 | 37 | | { |
| | 54 | 38 | | await using var ms = new MemoryStream(original); |
| | 54 | 39 | | var image = await Image.LoadAsync<Rgb24>(ms, ct); |
| | 50 | 40 | | image.Mutate(x => x.AutoOrient()); |
| | 50 | 41 | | return image; |
| | 50 | 42 | | } |
| | | 43 | | } |