C
C#10mo 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();
}
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();
}
3 Replies
Angius
AngiusOP10mo ago
ImageSharp looking might compelling right now lol
Kouhai
Kouhai10mo 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
Angius
AngiusOP10mo ago
Thanks! I did go with ImageSharp in the end, though, lol

Did you find this page helpful?