当我执行一些图像处理时,我似乎得到了一个内存不足的异常,但我不确定为什么,或者确切地说在哪里。堆栈跟踪如下:
System.OutOfMemoryException: Out of memory.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height)
at System.Drawing.Bitmap..ctor(Image original)
几秒钟之后会出现类似的内存异常:
System.OutOfMemoryException: Out of memory.
at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
我认为产生此代码的代码如下:
public static MemoryStream ResizeImage(this Bitmap bitmap, int destHeight, int destWidth, ImageFormat imageFormat)
{
MemoryStream mem = new MemoryStream();
var xRes = bitmap.VerticalResolution;
var yRes = bitmap.HorizontalResolution;
var largestRes = xRes > yRes ? xRes : yRes;
var factor = Math.Abs(xRes / yRes);
bitmap.SetResolution(largestRes, largestRes);
if (destHeight == 0)
destHeight = (int)(xRes != largestRes ? bitmap.Height / factor : bitmap.Height);
if (destWidth == 0)
destWidth = (int)(yRes != largestRes ? bitmap.Width / factor : bitmap.Width);
using (Bitmap b = new Bitmap(destWidth, destHeight))
{
using (Graphics g = Graphics.FromImage((System.Drawing.Image)b))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(bitmap, 0, 0, destWidth, destHeight);
}
b.Save(mem, imageFormat);
}
return mem;
}
我知道这是在进行大量的图像处理,但这有什么本质上的错误吗?
答案 0 :(得分:1)
代码没问题,但是当不支持图像的像素格式时,GDI +会抛出OutOfMemoryException。
检查图像以确保它受支持。