Showing posts with label C# GDI. Show all posts
Showing posts with label C# GDI. Show all posts

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.