How to set resize quality in SkiaSharp
Asked Answered
B

0

7

I'm using SkiaSharp to resize an existing image. On resize I'd like to be able to test/set the quality on different levels.

Here's my code:

public static class ResizeImage {

    public static string Resize(string image, int maxWidth = 0, int maxHeight = 0, int quality = 90, bool copy = false) {

        var bitmap = SKBitmap.Decode(image);

        if (bitmap.Width > maxWidth || bitmap.Height > maxHeight)
        {
            int width;
            int height;
            var extension = Path.GetExtension(image);               
            SKEncodedImageFormat imageFormat = GetImageFormat(extension);
            if (imageFormat != SKEncodedImageFormat.Astc)
            {
                if (bitmap.Width >= bitmap.Height)
                {
                    width = maxWidth;
                    height = Convert.ToInt32(bitmap.Height * maxWidth / (double)bitmap.Width);
                }
                else
                {
                    width = Convert.ToInt32(bitmap.Width * maxHeight / (double)bitmap.Height);
                    height = maxHeight;
                }
                var toBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType);
                bitmap.ScalePixels(toBitmap, SKFilterQuality.High);
                /*
                float canvasScale = Math.Max(width, height) / Math.Max(bitmap.Width, bitmap.Height);
                var canvas = new SKCanvas(toBitmap);
                canvas.SetMatrix(SKMatrix.MakeScale(canvasScale, canvasScale));
                canvas.DrawBitmap(bitmap, 0, 0);
                canvas.ResetMatrix();
                canvas.Flush();
                */
                var newImage = SKImage.FromBitmap(toBitmap);
                var imageData = newImage.Encode(imageFormat, quality);
                var newFileName = copy ? Path.ChangeExtension(image, "") + "-" + maxWidth + "-" + extension : image;
                using (var stream = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
                    imageData.SaveTo(stream);
                imageData.Dispose();
                newImage.Dispose();
                toBitmap.Dispose();
                bitmap.Dispose();
                return newFileName;
            }
        }

        return image;

    }

At first I tried resizing the image with new SKCanvas but I was not getting the result I wanted. I then discovered bitmap.ScalePixels that comes with predefined quality settings SKFilterQuality.

I'd like to control the quality with the quality param, but setting it in the Encode doesn't change anything (same result with quality = 1 and quality = 100).

What am I missing?

Brigantine answered 12/11, 2019 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.