Saturday, April 01, 2006

Setting JPEG image quality

I have many applications that create thumbnails or manipulate images. When I save these as jpegs the quality kind of sucks though. Took me a while but found a way to set it by way of using one of the overloads to pass the encoder to use (in this case the jpeg encoder) and parameters to that encoder.

Here is the method taht finds the right encoder based on mime type:

1 private static ImageCodecInfo GetEncoderInfo(String MimeType)

2 {

3 ImageCodecInfo Result = null;

4 ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders();

5 for(int i = 0; Result == null && i <>

6 {

7 if (Encoders[i].MimeType == MimeType)

8 {

9 Result = Encoders[i];

10 }

11 }

12 return Result;

13 }

Here is the code that actually saves the file:

30 EncoderParameters encoderParameters;

31 encoderParameters = new EncoderParameters(1);

32 encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

33 img.Save(ms, GetEncoderInfo("image/jpeg"), encoderParameters );

The thing that tripped me up for a while was the 100L for the quality. If I left the L off then the quality would not be changed strangely enough.


Post a Comment

<< Home