Paint方法抛出System.OutOfMemoryException
本文关键字:System OutOfMemoryException 方法 Paint | 更新日期: 2023-09-27 18:19:05
我有一个艰难的时间试图找出如何防止内存泄漏时,重绘PictureBox
这就是我的绘图方法的样子:
Bitmap image;
image = new Bitmap((Bitmap)baseImage.Clone());
Graphics g = Graphics.FromImage(image);
//here I'm drawing using created "g"
//reason why am doing it on new bitmap, not on paintBox.Image is that..
//..I don't want this drawings to be permanently added to my base image
g.Dispose();
paintBox.Image = image;
然后我使用的方法是改变baseImage和刷新paintBox多次(数百)。调用这个方法给我一个'System '。在System.Drawing.dll中出现OutOfMemoryException这个方法是递归的,但是我很确定它不会导致这个异常,因为当我改变这个方法,只修改基础图像没有刷新油漆盒它工作得很好(但是我想看到它的变化,使最新的)。
那么,在这种情况下,防止内存泄漏的最佳方法是什么?我正在尝试这样做:paintBoxx.Image.Dispose();
paintBox.Image = image;
但它给我'系统'。NullReferenceException'(因为我试图使用已处理的图像).
修改代码:
Bitmap image;
image = new Bitmap((Bitmap)baseImage.Clone());
using (Graphics g = Graphics.FromImage(image) )
{
// I am drawing on the bitmap so I don't permanently change my base image
// do your draw stuff here..
g.FillEllipse(Brushes.Yellow, 3, 3, 9, 9);
// ..
}
// don't leak the image and..
// ..don't Dispose without checking for null
if (paintBox.Image != null) paintBox.Image.Dispose();
paintBox.Image = image;
注意using
子句,即使图纸出现问题,也将处理Graphics
对象。
你试过使用MemoryStream吗?
看一下我的示例代码:
image = new Bitmap((Bitmap)baseImage.Clone());
using (MemoryStream imageStream = new MemoryStream())
{
// put iimagem in memory stream
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Gif);
// create an array of bytes with image length
byte[] imageContent = new Byte[imageStream.Length];
// reset memory stream
imageStream.Position = 0;
// load array of bytes with the imagem
imageStream.Read(imageContent, 0, (int)imageStream.Length);
// change header page "content-type" to "image/jpeg" and print the image.
Response.ContentType = "image/gif";
Response.BinaryWrite(imageContent);
}