25 November 2008

C# a generic error occurred in GDI+ Solution

A generic error occurred in GDI+
I encountered this error while I was working with images,
when I try to save image file with EncoderParameter and ImageCodecInfo classes in C#.

This problem is mostly occurred for the security reasons,
you may not enough permission to write file and so on.
Here is solution.
  • Create a System.IO.MemoryStream object.
  • Create a System.IO.FileStream object
  • Save image into MemoryStream
  • Read bytes[] from the MemoryStream
  • Save the image file with FileStream
And Here is the C# sample code;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;

public static void SaveJpeg
(string path, Image img, int quality)
{
EncoderParameter qualityParam
= new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

ImageCodecInfo jpegCodec
= GetEncoderInfo(@"image/jpeg");

EncoderParameters encoderParams
= new EncoderParameters(1);

encoderParams.Param[0] = qualityParam;

System.IO.MemoryStream mss = new System.IO.MemoryStream();

System.IO.FileStream fs
= new System.IO.FileStream(path, System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);

img.Save(mss, jpegCodec, encoderParams);
byte[] matriz = mss.ToArray();
fs.Write(matriz, 0, matriz.Length);

mss.Close();
fs.Close();
}
Do not forget to close streams, other wise you will get a out of memory error.

11 comments:

ÇakıRoğlaN said...

Thank you very much. I was looking for this answer for a long time.

Anonymous said...

Oh you saved my life, I have been looking for a simple solution with this error. You provide very simple solution for manage this error. Thanks ^^

Anonymous said...

Thank you very much! Helped me a lot!!!!! I was looking for something like this for hours...

Anonymous said...

How does this solution bypass security issues ?

Anonymous said...

Very helpful. Thanks :)

Anonymous said...

This error is due to GDI handles crossing the limit of 10000.you can confirm this in your code by viewing GDI objects in task manager while running your code.what you code does is to avoid the open GDI handles. good workaround but i am still looking for a better solution.

Anonymous said...

This problem is mostly occurred for the security reasons.


thanks for saving my life....

Gopal Chauhan

Tarek Siala said...

where is GetEncoderInfo ?

Anonymous said...

thank you very much
it also saving my life

Anonymous said...

Thanks!

I must admit them "a generic error occurred in GDI+" is a real pain in the a***.

Your solution made it work, and thank you for that!

Gaurav said...

Thank you it helped. Instead of using separate methods I just wrote line as pictureBox1.Image.Save("output.bmp"). However, what if I want to save it as Jpg or in any other format?