[英]Random OutofMemory and Invalid Parameter when creating a new Bitmap object in c#
我正在创建一个简单的工具应用程序,用于创建将在网络地图中使用的图像标题。 我的问题是,当我加载并调整代表最大缩放级别的最大图像(每侧8192像素)并调整其大小时,会得到随机的OutofMemoryException
和InvalidParameterException
// Always will resize the image to fit the zoom level size
// Will not resize if the image has already the correspondig
// width and height of the zoom level ( ie level 5, w= 8192px
// h = 8192px )
using (Bitmap actualBitmap = new Bitmap(resizeImage(imgActualLevel, actualLevel)))
{
// ... code that crop the file in to 256px tiles
}
private Bitmap resizeImage(Image originalImage, int zoomLevel)
{
int maxTilesPerZoomLevel = (int)(Math.Pow(2, zoomLevel));
int IMG_WIDTH = maxTilesPerZoomLevel * TILE_SIZE;
int IMG_HEIGHT = maxTilesPerZoomLevel * TILE_SIZE;
Image resizedImage = originalImage;
if ((originalImage.Height != IMG_HEIGHT) || (originalImage.Width != IMG_WIDTH))
{
resizedImage = new Bitmap(IMG_WIDTH, IMG_HEIGHT);
Graphics graphics = Graphics.FromImage(resizedImage);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(originalImage, new Rectangle(0, 0, IMG_WIDTH,IMG_HEIGHT));
}
return (Bitmap)resizedImage;
}
但是问题是:有时工作正常并且应用程序运行良好,然后第二天我回来继续操作,但我未做任何修改就得到了错误。 我已经放置了许多Dispose()
方法和using() {}
并且确保没有在ram中留下图像,但是出现了错误。
您知道发生了什么问题吗?
看起来您的using语句存在内存泄漏。 您正在根据resizeImage的结果创建一个新的位图,该结果也创建了一个新的位图。 在resizeImage中创建的位图永远不会正确处理。 我也看不到为什么需要立即复制返回的位图。 尝试这样的事情:
using (Bitmap actualBitmap = resizeImage(imgActualLevel, actualLevel))
{
// ... code that crop the file in to 256px tiles
}
您也不会在resizeImage中放置Graphics对象。 您应该这样将其包装在using语句中:
private Bitmap resizeImage(Image originalImage, int zoomLevel)
{
int maxTilesPerZoomLevel = (int)(Math.Pow(2, zoomLevel));
int IMG_WIDTH = maxTilesPerZoomLevel * TILE_SIZE;
int IMG_HEIGHT = maxTilesPerZoomLevel * TILE_SIZE;
Image resizedImage = originalImage;
if ((originalImage.Height != IMG_HEIGHT) || (originalImage.Width != IMG_WIDTH))
{
resizedImage = new Bitmap(IMG_WIDTH, IMG_HEIGHT);
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(originalImage, new Rectangle(0, 0, IMG_WIDTH,IMG_HEIGHT));
}
}
return (Bitmap)resizedImage;
}
还有一个提示:不要依赖位图构造函数返回的异常类型。 当它实际上表示OutOfMemory时,它可以抛出ArgumentOutOfRange,反之亦然。 有时可能会很混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.