Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
540 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...