C#C
C#2y ago
Angius

✅ SkiaSharp canvas scale not scaling

I have a method that takes an int[,] array with ones and zeroes. Based on that, I want to create an image, that is optionally resized and blurred.
Creating the image at 1:1 scale works, blurring it works as well, but for the love of me I cannot get it to scale...
byte[] CreateImage(int[,] arr, float? scale = null, float? blur = null)
{
    var wSize = arr.GetLength(0);
    var hSize = arr.GetLength(1);
    
    var bmp = new SKBitmap(wSize, hSize);
    using (var canvas = new SKCanvas(bmp))
    {
        for (var w = 0; w < wSize; w++)
        {
            for (var h = 0; h < hSize; h++)
            {
                canvas.DrawPoint(w, h, arr[w, h] == 0 ? SKColors.White : SKColors.Black);
            }
        }

        if (scale is {} s)
        {
            canvas.Scale(s);
        }
    }

    if (blur is {} b)
    {
        var newBmp = new SKBitmap((int)(wSize * scale ?? 1), (int)(hSize * scale ?? 1));
        using var canvas = new SKCanvas(newBmp);
        using var paint = new SKPaint();
        
        paint.ImageFilter = SKImageFilter.CreateBlur(b, b);
        canvas.DrawImage(SKImage.FromBitmap(bmp), 0, 0, paint);
        
        using var blurredImage = SKImage.FromBitmap(newBmp);
        return blurredImage.Encode().ToArray();
    }

    using var image = SKImage.FromBitmap(bmp);
    return image.Encode().ToArray();
}
Was this page helpful?