Site Loader
Auckland, New Zealand
There are times where we might need to store images in database tables. This is done especially while we try to capture a failure image taken by automation framework and store in DB which used for reporting purpose. In order to store a captured image we might need to compress the image in small size. This can be done using ImageCodecInfo Class. This class provides the necessary storage members and methods to retrieve all pertinent information about the installed image encoders and decoders (called codecs). Using GetImageEncoder() method, which returns the MIME (Multipurpose Internet Mail Extensions) type, we can convert the image to the MIME type which we are interested in, let’s say JPEG or BMP etc. In this demonstration we are going to store image in BMP, hence the code looks like this.
public static byte[] SaveImage(Image img)

{

MemoryStream ms = new MemoryStream();

ImageCodecInfo bmpCodec = GetEncoderInfo("image/bmp");

EncoderParameters encoderParams = new EncoderParameters(1);

EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 30L);

encoderParams.Param[0] = qualityParam;

img.Save(ms, bmpCodec, encoderParams);

return ms.ToArray();

}

private static ImageCodecInfo GetEncoderInfo(string mimeType)

{

// Get image codecs for all image formats

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

// Find the correct image codec

for (int i = 0; i < codecs.Length; i++)

if (codecs[i].MimeType == mimeType)

return codecs[i];

return null;

}

As you can see the above code, the SaveImage(Image img) method has taken an Image class type as parameter, which is nothing but the image which we have captured. Then we are passing the GetEncoderInfo() method a MIME type, which is nothing but the “image/bmp”. This function actually returns the image codec we are looking for. Using Save method of Image class, we store the image as byte array byte[]. As you can see the Encoder.Quality level is set to 30L, hence the quality if image will be normal. That’s it !!! Thanks, Karthik KK

Post Author: Karthik kk

Leave a Reply

Your email address will not be published. Required fields are marked *