图形.取出内存问题
本文关键字:问题 内存 图形 | 更新日期: 2023-09-27 18:05:16
当我执行一些图像操作时,我似乎正在获得内存异常,但我不确定为什么,或者确切地在哪里。堆栈跟踪如下:
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;
}
我知道这是做很多图像处理,但有什么内在的错误吗?
代码是可以的,但是当图像的像素格式不支持时,GDI+可以抛出OutOfMemoryException
检查图片是否支持