From f937a1d9991be53378e26a5adcc197d37f1cb6ab Mon Sep 17 00:00:00 2001 From: TheXamlGuy Date: Wed, 3 Jul 2024 12:39:23 +0100 Subject: [PATCH] Fixed imagereader, again --- Toolkit.Avalonia/ImageResizer.cs | 35 +++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/Toolkit.Avalonia/ImageResizer.cs b/Toolkit.Avalonia/ImageResizer.cs index b6a86f1..654143b 100644 --- a/Toolkit.Avalonia/ImageResizer.cs +++ b/Toolkit.Avalonia/ImageResizer.cs @@ -3,42 +3,53 @@ using SkiaSharp; namespace Toolkit.Avalonia; -public class ImageResizer : +public class ImageResizer : IImageResizer { - public Bitmap Resize(Stream stream, int targetWidth, int targetHeight, bool maintainAspectRatio) + public Bitmap Resize(Stream stream, + int targetWidth, + int targetHeight, + bool maintainAspectRatio) { Bitmap bitmap = new(stream); if (bitmap.Size.Width != targetWidth || bitmap.Size.Height != targetHeight) { stream.Seek(0, SeekOrigin.Begin); - using SKBitmap sKBitmap = SKBitmap.Decode(stream); + float widthRatio = (float)targetWidth / sKBitmap.Width; float heightRatio = (float)targetHeight / sKBitmap.Height; - float scale = maintainAspectRatio ? Math.Min(widthRatio, heightRatio) : Math.Max(widthRatio, heightRatio); + float scale = maintainAspectRatio ? Math.Max(widthRatio, heightRatio) : Math.Min(widthRatio, heightRatio); int newWidth = (int)(sKBitmap.Width * scale); int newHeight = (int)(sKBitmap.Height * scale); - using SKBitmap resized = sKBitmap.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High); + using SKBitmap resized = new(newWidth, newHeight); + using SKCanvas canvas = new(resized); - SKBitmap cropped = resized; + canvas.Clear(SKColors.Transparent); + canvas.DrawBitmap(sKBitmap, new SKRect(0, 0, newWidth, newHeight)); + + SKBitmap cropped; if (maintainAspectRatio) { - int cropX = (resized.Width - targetWidth) / 2; - int cropY = (resized.Height - targetHeight) / 2; + int cropX = (newWidth - targetWidth) / 2; + int cropY = (newHeight - targetHeight) / 2; cropped = new SKBitmap(targetWidth, targetHeight); using SKCanvas croppedCanvas = new(cropped); - SKRect originalRect = new(cropX, cropY, cropX + targetWidth, cropY + targetHeight); - SKRect targetRect = new(0, 0, targetWidth, targetHeight); - croppedCanvas.DrawBitmap(resized, originalRect, targetRect); + SKRect cropRect = new(cropX, cropY, cropX + targetWidth, cropY + targetHeight); + croppedCanvas.Clear(SKColors.Transparent); + croppedCanvas.DrawBitmap(resized, cropRect, new SKRect(0, 0, targetWidth, targetHeight)); + } + else + { + cropped = resized; } using SKImage image = SKImage.FromBitmap(cropped); - using MemoryStream outputStream = new MemoryStream(); + using MemoryStream outputStream = new(); image.Encode(SKEncodedImageFormat.Png, 100).SaveTo(outputStream); outputStream.Seek(0, SeekOrigin.Begin); bitmap.Dispose();