Paint方法抛出System.OutOfMemoryException

时间:2015-10-25 10:54:23

标签: c# system.drawing

重绘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.Drawing.dll中给出'System.OutOfMemoryException' 这个方法是递归的,但是我很确定它不会导致这个异常,因为当我改变这个方法只修改基本图像而没有刷新绘图框时它工作正常(但是我希望看到它更新的更新) )。

那么,在这种情况下,防止内存泄漏的最佳方法是什么? 我正在尝试这样的事情:

paintBoxx.Image.Dispose();
paintBox.Image = image;

但是它给了我'System.NullReferenceException'(因为我正在尝试使用处理过的图像)。

任何建议都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

将您的代码更改为:

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对象,即使绘图遇到问题。

答案 1 :(得分:-1)

您是否尝试过使用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);
}