[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Optimize JPEG compression level and file size in C#

example

This example lets you check image quality with different JPEG compression levels. Use the File menu's 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 resulting image and the file's size.

The key to the program is the following SaveJpg method, 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. 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); } }

This method 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 method 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 following code shows the GetEncoderInfo method.

// Return an ImageCodecInfo object for this mime type. 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; }

This code loops through the available encoders until it finds one with the right mime type, in this case "image/jpeg."

In the picture shown at the top of this post, the compression level is 30. It still produces a nice result and the compressed file's size is only around 18% of the original file's size. Results vary depending on the image.

In addition to the code shown here, this example uses techniques described in the following posts:

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.