WhiteSites Blog

Generic Error Occurred in GDI with .Net and JPGs

Posted on Sep 29, 2015 by Paul White

Everyone who works on ASP.NET websites will eventually come accross this error.  A generic error occurred in GDI+.  This usually happens when trying to save a image file to disk.  Something normal like handling photo uploads then saving them.  In my case I was trying to lower the quality on 20,000 JPG images to about 75%.  The problem I ran into was it wouldn't let me overwrite my image to the original location.  There is a very easy solution to this.  

The Symptoms

You get an error message like this

System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)  

The Cause

In your code you likely loaded a file into a Bitmap Object, made some edits and then tried saving that image back to the original location.  Unfortunatley Bitmap Objects Lock the file until they are Disposed.

The Solution

  1. Load the file into a new Bitmap
  2. Create a new (2nd) Bitmap and load the first bitmap into it.
  3. Dispose the First Bitmap.
  4. Make your edits on the 2nd bitmap
  5. Save the file
  6. Dispose of the 2nd Bitmap

Code Example

ImageCodecInfo codecs = ImageCodecInfo.GetImageEncoders();
   ImageCodecInfo ici = null;
            foreach( ImageCodecInfo codec in codecs )
                 if(codec.MimeType == "image/jpeg") 
                       ici = codec;
                 
            
            
   EncoderParameters ep = new EncoderParameters(); 
   ep.Param0 = new EncoderParameter (System.Drawing.Imaging.Encoder.Quality, 75L);

 

Bitmap largeBit = new Bitmap(file);
Bitmap goodBit = new Bitmap(largeBit);
largeBit.Dispose();
goodBit.Save(file, ici, ep);
goodBit.Dispose();

Summary

Hopefully this helps others.


Permalink
4098 Visitors
4098 Views

Categories associated with Generic Error Occurred in GDI with .Net and JPGs

Discussion

No Comments have been submitted
name
Email Needed to confirm comment, but not made public.
Website
 
 
When you Post your Comment, you'll be sent a confirmation link. Once you click this link your thoughts will be made public.. Posts that are considered spam will be deleted, Please keep your thoughts and links relavent to this Article