A generic error occurred in GDI+ at System.Drawing.Image.Save

Razor picture Razor · Mar 28, 2014 · Viewed 73.4k times · Source

Exception:

A generic error occurred in GDI+. at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(String filename, ImageFormat format) at System.Drawing.Image.Save(String filename)

Code:

byte[] bitmapData = new byte[imageText.Length];
MemoryStream streamBitmap;
bitmapData = Convert.FromBase64String(imageText);
streamBitmap = new MemoryStream(bitmapData);
System.Drawing.Image img = Image.FromStream(streamBitmap);
img.Save(path);

We convert a base64 string into a MemoryStream and then create a System.Drawing.Image (Image.FromStream(streamBitmap)). At the end the image is saved in a temp file.

The strange thing is that the problem seems to occur when the activity (number of concurrent users) is high on the web server and the problem is solved temporarily after an IISRESET or an application pool recycle...

==> Garbage collector issue ?

I already checked the permission of the TEMP folder...

Answer

Suresh Kumar Veluswamy picture Suresh Kumar Veluswamy · Mar 28, 2014

When you are loading an imagefrom a Stream, You have to keep the stream open for the lifetime of the image, see this MSDN Image.FromStream.

I think the exception is caused because the memory stream gets closed even before the image gets disposed. You can change your code like this:

byte[] bitmapData = new byte[imageText.Length];
bitmapData = Convert.FromBase64String(imageText);

  using (var streamBitmap = new MemoryStream(bitmapData))
  {
      using (img = Image.FromStream(streamBitmap))
      { 
         img.Save(path);
      }
  }

Here are some links to threads discussing similar problems:

gdi+ error saving image from webpage

When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI