我有这个小方法,可以调整图像大小并裁剪它,但是在它工作了几个小时后,它突然开始给我 OutOfMemory 异常。我究竟做错了什么?我认为异常已开启return bmp.Clone(cropArea, bmp.PixelFormat);
private static Bitmap Resize(Bitmap image, int width, int height)
{
double scaleH = (double)height / image.Height;
double scaleW = (double)width / image.Width;
double scale = 1.0;
if (image.Width * scaleH >= width)
scale = scaleH;
else if (image.Height * scaleW >= height)
scale = scaleW;
var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);
using (var bmp = new Bitmap((int)scaleWidth, (int)scaleHeight))
{
using (var graph = Graphics.FromImage(bmp))
{
graph.DrawImage(image, new Rectangle(0, 0, scaleWidth, scaleHeight));
}
int xStart = (bmp.Width - width) / 2;
int yStart = (bmp.Height - height) / 2;
Rectangle cropArea = new Rectangle(xStart, yStart, width, height);
return bmp.Clone(cropArea, bmp.PixelFormat);
}
}
解决方案这是一个舍入问题,裁剪矩形比它自己的图像大
var scaleWidth = (int)Math.Ceiling(image.Width * scale);
var scaleHeight = (int)Math.Ceiling(image.Height * scale);