Saturday, October 30, 2010

A General Error Occurred In GDI+

The error message "A general error occurred in GDI+"is pretty tricky in C# - it occurs sporadically and the reasons are often not clear on the first view. Therefore I want to devote this post to this error and its causes and list the in my experience 2 most common causes of this graphic error.

Above error can occur, when one tries to save the image via the function Save() to a non existing path.
The following code tries to save the content of the pictureBox as an image and then throws the exception, given the path really is not available:

pictureBox1.Image.Save("C:\\NonExistingPath\\test.jpg");

When loading an image, a wrong path leads to a FileNotFoundException.

Another most common cause of "A Generic Error occurred in GDI+" is the not disposing of an image object.
If you for example load the image via the function Image.FromFile(), this stays open in the memory, until it is colleccted. Especially, before disposing no saving with Save() is possible.
The following code example loads an image to the pictureBox and then tries to save it - but the error described here occurs, since it was (most likely) not disposed (I say most likely, as the garbage collector could do that in the mean time):

pictureBox1.Image = Image.FromFile("C:\\test\\test1.jpg");
pictureBox1.Image.Save("C:\\test\\test2.jpg");

For correctness, the image has to be "recopied" again interally:

pictureBox1.Image = Image.FromFile("C:\\test\\test1.jpg");
Image Copy = pictureBox1.Image;
Copy.Save("C:\\test\\test2.jpg");

I hope the post explained the basic difficulty of this error, for further reasons etc. I am always thankful!

No comments:

Post a Comment