Quality of Dynamic Images
Got this question from a comment to a previous post.
Any idea how to control the quality of a generated JPEG image from the DynamicImage control?
More in general the question can be generalized to "how to control the quality of a generated JPEG image in .NET".
As far as I know today, DynamicImage generates JPEG images only in one case--if your source image is, say, GIF and you want to output a JPEG. Or if you're attempting to send an image to a device that doesn't accept it but does accept JPEGs.
Looking at the current implementation of the DynamicImage control in ASP.NET 2.0, it normalizes any input image (bytes, GDI+ object, URL) to a GDI+ object and then uses the Bitmap.Save method to output the image to a particular type--PNG, JPG, GIF, BMP and so forth. This technique can be used from within your own ASIX handlers or in ASP.NET 1.x handlers that return dynamic images. (I'm just finishing a MSDNMag article about dynamic images in ASP.NET 1.x)
I wouldn't say that the default quality of JPG is bad (based on my limited experience) but I understand that it is a personal factor, often app-specific. Finally, I could just be wrong. I remember that all colleagues were telling me (years ago) that my feeling with image quality wasn't that great...
To come to the point, you can control the compression ratio of JPEGs. I agree that the default ratio is probably OK for Web images but not necessarily for a high-quality image.
// Set the quality to 40 (must be a long)
Encoder qualityEncoder = Encoder.Quality;
EncoderParameter ratio = new EncoderParameter(qualityEncoder, 40L);
// Add the quality parameter to the list
codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
// Save to JPG
bmp.Save(fileName, jpegCodecInfo, codecParams);
The first step is to get the ImageCodecInfo structure for the JPEG image. The GDI+ interface provides no direct method to get this object. You must resort to a little trick—enumerate all the image encoders and check their MIME type properties against the JPEG MIME type string (image/jpeg). The ImageCodecInfo structure contains information inherent in the encoding and decoding of the image. The code is an excerpt from this MSDN article.