aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/Imaging/ImageService.cs
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-04-27 18:52:57 +0800
committercrupest <crupest@outlook.com>2021-04-27 18:52:57 +0800
commit1b751781f0681a047f3d3d6097009478886ee2f5 (patch)
tree4710ab0c761a264f090f9aa74a45e62fd39450f8 /BackEnd/Timeline/Services/Imaging/ImageService.cs
parent6c9778b55dd8367d38280c66e0f308c5332029ed (diff)
downloadtimeline-1b751781f0681a047f3d3d6097009478886ee2f5.tar.gz
timeline-1b751781f0681a047f3d3d6097009478886ee2f5.tar.bz2
timeline-1b751781f0681a047f3d3d6097009478886ee2f5.zip
refactor: ...
Diffstat (limited to 'BackEnd/Timeline/Services/Imaging/ImageService.cs')
-rw-r--r--BackEnd/Timeline/Services/Imaging/ImageService.cs54
1 files changed, 54 insertions, 0 deletions
diff --git a/BackEnd/Timeline/Services/Imaging/ImageService.cs b/BackEnd/Timeline/Services/Imaging/ImageService.cs
new file mode 100644
index 00000000..9fefe3e9
--- /dev/null
+++ b/BackEnd/Timeline/Services/Imaging/ImageService.cs
@@ -0,0 +1,54 @@
+using SixLabors.ImageSharp;
+using SixLabors.ImageSharp.Formats;
+using System;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Timeline.Services.Imaging
+{
+
+ public class ImageService : IImageService
+ {
+ public async Task<IImageFormat> DetectFormatAsync(byte[] data, CancellationToken cancellationToken = default)
+ {
+ if (data == null)
+ throw new ArgumentNullException(nameof(data));
+
+ var format = await Task.Run(() =>
+ {
+ var format = Image.DetectFormat(data);
+ if (format is null)
+ {
+ throw new ImageException(ImageException.ErrorReason.CantDecode, data, null, null, null);
+ }
+ return format;
+ }, cancellationToken);
+ return format;
+ }
+
+ public async Task<IImageFormat> ValidateAsync(byte[] data, string? requestType = null, bool square = false, CancellationToken cancellationToken = default)
+ {
+ if (data == null)
+ throw new ArgumentNullException(nameof(data));
+
+ var format = await Task.Run(() =>
+ {
+ try
+ {
+ using var image = Image.Load(data, out IImageFormat format);
+ if (requestType != null && !format.MimeTypes.Contains(requestType))
+ throw new ImageException(ImageException.ErrorReason.UnmatchedFormat, data, requestType, format.DefaultMimeType);
+ if (square && image.Width != image.Height)
+ throw new ImageException(ImageException.ErrorReason.BadSize, data, requestType, format.DefaultMimeType);
+ return format;
+ }
+ catch (UnknownImageFormatException e)
+ {
+ throw new ImageException(ImageException.ErrorReason.CantDecode, data, requestType, null, null, e);
+ }
+ }, cancellationToken);
+ return format;
+ }
+ }
+}