C
C#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();
}
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();
}
A
Angius15d ago
ImageSharp looking might compelling right now lol
K
Kouhai /人◕ ‿‿ ◕人\15d ago
Canvas.Scale only scales subsequent draw calls, it doesn't scale the canvas itself If you want to scale the bitmap after you've called Canvas.DrawPoint you can do bmp.ScalePixels
A
Angius15d ago
Thanks! I did go with ImageSharp in the end, though, lol
Want results from more Discord servers?
Add your server
More Posts