.NET, Archive, Software Design
     

A Generic Error Occurred in GDI+

You know you’re doing good when your application crashes with an exception as detailed as “a generic error occurred in gdi+”. That is about as, well generic, as it gets :- )

In my particular case I was constructing an Image down in my DAO using the FromStream method, like so:

Image result;
using (FileStream file = File.OpenRead(filename)) {
	result = Image.FromStream(file);
	file.Close();
}
return result;

I was doing this so that I could know for a fact that the file was being disposed of properly. I didn’t want to have any orphaned file references locking up the file in case I later needed to delete it.

The problem was that up in my UI I was attempting to call the Save method on Image to dump its contents out to the ASP.NET response stream, like so:

img.Save(HttpContext.Response.OutputStream, ImageFormat.Jpeg);

And that is when GDI+ threw the exception. As it turns out the Image object needs the file resource left open for so long as the Image object is in use, and I had been closing that file down in the DAO (before the UI tried to invoke the Save method).

The solution in this particular scenario was to use the Image’s FromFile method to construct the Image, so that the DAO now resembled:

return Image.FromFile(filename);

This design choice has the unfortunate effect of forcing the upper tiers (most notably the UI tier) to dispose of the Image object when they are done.

using(Image img = /* ... */){
	img.Save(HttpContext.Response.OutputStream, ImageFormat.Jpeg);
}

While this is done easily enough C# using statement, it does leave the chance for unmanaged resource leaks. But at least it resolve the GDI+ error.

Never miss an article! Subscribe to my newsletter and I'll keep you updated with the latest content.

 

About Jason

Jason is an experienced entrepreneur & software developer skilled in leadership, mobile development, data synchronization, and SaaS architecture. He earned his Bachelor of Science (B.S.) in Computer Science from Arkansas State University.
View all posts by Jason →

Leave a Reply

Your email address will not be published. Required fields are marked *