From 82ddf7dea62bfbabd9987cca611254ccfb55cd30 Mon Sep 17 00:00:00 2001 From: XShine555 Date: Wed, 18 Mar 2026 01:24:16 +0100 Subject: [PATCH] PictureHandler --- .../Infrastructure/IPictureHandler.cs | 9 ++++ Infrastructure/Infrastructure.csproj | 1 + Infrastructure/Pictures/PictureHandler.cs | 42 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 Application/Contracts/Infrastructure/IPictureHandler.cs create mode 100644 Infrastructure/Pictures/PictureHandler.cs diff --git a/Application/Contracts/Infrastructure/IPictureHandler.cs b/Application/Contracts/Infrastructure/IPictureHandler.cs new file mode 100644 index 0000000..63ba2e1 --- /dev/null +++ b/Application/Contracts/Infrastructure/IPictureHandler.cs @@ -0,0 +1,9 @@ +using Ardalis.Result; + +namespace Musify.Application.Contracts.Infrastructure +{ + public interface IPictureHandler + { + Task> ResizePictureAsync(Stream pictureStream, int width, int height, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/Infrastructure/Infrastructure.csproj b/Infrastructure/Infrastructure.csproj index 8b630b2..7564525 100644 --- a/Infrastructure/Infrastructure.csproj +++ b/Infrastructure/Infrastructure.csproj @@ -11,6 +11,7 @@ + diff --git a/Infrastructure/Pictures/PictureHandler.cs b/Infrastructure/Pictures/PictureHandler.cs new file mode 100644 index 0000000..6afa11b --- /dev/null +++ b/Infrastructure/Pictures/PictureHandler.cs @@ -0,0 +1,42 @@ +using Ardalis.Result; +using Microsoft.Extensions.Logging; +using Musify.Application.Contracts.Infrastructure; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; + +namespace Musify.Infrastructure.Pictures +{ + public class PictureHandler(ILogger logger) + : IPictureHandler + { + public async Task> ResizePictureAsync(Stream pictureStream, int width, int height, CancellationToken cancellationToken) + { + try + { + if (pictureStream.CanSeek && pictureStream.Position > 0) + pictureStream.Position = 0; + + using var picture = await Image.LoadAsync(pictureStream, cancellationToken); + + picture.Mutate(options => options.Resize(new ResizeOptions + { + Size = new Size(width, height), + Mode = ResizeMode.Max + } )); + + var memoryStream = new MemoryStream(); + + await picture.SaveAsWebpAsync(memoryStream, cancellationToken); + + memoryStream.Position = 0; + + return Result.Success(memoryStream); + } + catch (Exception exception) + { + logger.LogError(exception, "An error occurred while resizing the picture."); + return Result.Error("An error occurred while resizing the picture."); + } + } + } +} \ No newline at end of file