我正在使用SkiaSharp调整现有图像的大小。调整大小后,我希望能够在不同级别上测试/设置质量。
这是我的代码:
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;
}
起初,我尝试使用new SKCanvas
调整图像的大小,但没有得到想要的结果。然后,我发现bitmap.ScalePixels
带有预定义的质量设置SKFilterQuality
。
我想使用quality
参数来控制质量,但是在Encode
中进行设置不会改变任何内容(质量= 1和质量= 100的结果相同)。>
我想念什么?