View the tradeoff between compression level and file size in a JPG image in C#
Use the File menu's Load a Open command to load an image file. Then use the "JPEG Compression Index (CI)" ComboBox to select a compression level. The program saves the image into a temporary file with that compression level and displays the file's size.
The key to the program is the SaveJpg function, which saves a JPG file with a given compression index. (It's a pretty useful function to have in your toolkit.)
// Save the file with a specific compression level.The function creates an EncoderParameters object to hold information to send to the encoder that will create the JPG file. It fills in the compression index. Next the function calls the GetEncoderInfo function (described shortly) to get information about the encoder for JPG files. It deletes the previous temporary file and uses the encoder to save the file again. The GetEncoderInfo function loops through the available encoders until it finds one with the right mime type, in this case "image/jpeg."
private void SaveJpg(Image image, string file_name, long compression)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info = GetEncoderInfo("image/jpeg");
File.Delete(file_name);
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
MessageBox.Show("Error saving file '" + file_name +
"'\nTry a different file name.\n" + ex.Message,
"Save Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
// Return an ImageCodecInfo object for this mime type.See also:
private ImageCodecInfo GetEncoderInfo(string mime_type)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i <= encoders.Length; i++)
{
if (encoders[i].MimeType == mime_type) return encoders[i];
}
return null;
}


Comments