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
using System.Drawing.Imaging;Do not forget to close streams, other wise you will get a out of memory error.
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();
}
11 comments:
Thank you very much. I was looking for this answer for a long time.
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 ^^
Thank you very much! Helped me a lot!!!!! I was looking for something like this for hours...
How does this solution bypass security issues ?
Very helpful. Thanks :)
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.
This problem is mostly occurred for the security reasons.
thanks for saving my life....
Gopal Chauhan
where is GetEncoderInfo ?
thank you very much
it also saving my life
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!
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?
Post a Comment