PictureBox memoryleak?

  • Thread starter Thread starter Mikael Koskinen
  • Start date Start date
M

Mikael Koskinen

I have a program with one PictureBox in it and one button, which
changes the image which is shown (actually at the moment there is only
two images which are loaded back and forth). After a coule of changes,
the application crashes with OutOfMemoryException.

At the moment the code looks like this:
this.pictureBox.Image = new System.Drawing.Bitmap(this.imageDirectory
+ "\\" + imageLocation);

This causes the program to run out of memory.

It won't help if I put this code in:
this.pictureBox.Dispose();
this.pictureBox = new PictureBox();
this.pictureBox.Image = new System.Drawing.Bitmap(this.imageDirectory
+ "\\" + imageLocation);

Shouldn't the dispose-method free the memory? If so, why the code
above still causes the program to run out of memory?
 
Try replacing your code with

if ( this.pictureBox.Image != null )
this.pictureBox.Image.Dispose();
this.pictureBox.Image = new System.Drawing.Bitmap(this.imageDirectory
+ "\\" + imageLocation);
 
Try to dispose the Bitmap instead of PictureBox

Something like that:

private void LoadBigPicture(string file)
{
if (PictureBox1.Image != null)
PictureBox1.Image.Dispose();

Bitmap bmp = new Bitmap(file);
PictureBox1.Image = bmp;
}
 
Back
Top