From 968140e8aaba398e10585e978aff33d7b32e824a Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 6 Mar 2020 22:28:32 +0800 Subject: Init development of post image feature. --- Timeline/Services/ImageValidator.cs | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Timeline/Services/ImageValidator.cs (limited to 'Timeline/Services/ImageValidator.cs') diff --git a/Timeline/Services/ImageValidator.cs b/Timeline/Services/ImageValidator.cs new file mode 100644 index 00000000..897a37b8 --- /dev/null +++ b/Timeline/Services/ImageValidator.cs @@ -0,0 +1,50 @@ +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace Timeline.Services +{ + public class ImageValidator + { + private readonly bool _requireSquare; + + public ImageValidator(bool requireSquare = false) + { + _requireSquare = requireSquare; + } + + /// + /// Validate a image data. + /// + /// The data of the image. Can't be null. + /// If not null, the real image format will be check against the requested format and throw if not match. If null, then do not check. + /// The format. + /// Thrown when is null. + /// Thrown when image data can't be decoded or real type does not match request type or image is not square when required. + public async Task Validate(byte[] data, string? requestType = null) + { + 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 (_requireSquare && image.Width != image.Height) + throw new ImageException(ImageException.ErrorReason.NotSquare, data, requestType, format.DefaultMimeType); + return format; + } + catch (UnknownImageFormatException e) + { + throw new ImageException(e, ImageException.ErrorReason.CantDecode, data, requestType, null); + } + }); + return format; + } + } +} -- cgit v1.2.3