【发布时间】:2015-01-14 11:26:36
【问题描述】:
我正在尝试从 base 64 字符串创建大量每像素 1 位的 bmp 图像并保存。根据要求,在短时间内创建大量图像(平均在短时间内创建 50,000 到 1,00,000 个)。我正在使用下面的代码。
public void CreateoneBppImageAndSave(String base64ImageString,String ImagePathToSave)
{
byte[] byteArray = Convert.FromBase64String(base64ImageString);
System.Drawing.Image img = byteArrayToImage(byteArray);
Bitmap objBitmap = new Bitmap(img);
BitmapData bmpData = objBitmap.LockBits(new Rectangle(0, 0, objBitmap.Width, objBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
Bitmap oneBppBitmap = new Bitmap(objBitmap.Width, objBitmap.Height, bmpData.Stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, bmpData.Scan0);
oneBppBitmap.Save(ImagePathToSave, ImageFormat.Bmp);
img.Dispose();
objBitmap.Dispose();
objBitmap.UnlockBits(bmpData);
oneBppBitmap.Dispose();
}
private Image byteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
}
这里的物理内存使用率非常高。通常生成的图像大小为 200x200 到 754x1024 。一段时间后,物理内存使用量达到极限并抛出内存不足异常。物理内存每 5-10 秒增加 0.01 GB。请帮助我在内存使用方面优化代码。
【问题讨论】:
-
你为什么手动调用
Dispose()而不使用using语句? -
我已经通过显式调用 dispose 来处理任何可以处理的对象。
-
在 object.dispose() 上使用一次性“使用”有什么好处
-
你不应该打电话给
UnlockBitsobjBitmap吗? -
根据您的更正,您在处理后致电
UnlockBits,这是另一个错字还是您真正在做什么?
标签: c# memory-management bitmap out-of-memory