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:
See those examples or download this one to see the details.



It is Very UseFull , tank you very much
Pingback: Compress JPG files to a certain size in C# - C# HelperC# Helper
gud one
which algorithms you use in this
This just uses the .NET image encoder. I don’t know what algorithm it uses, although it’s clear that it is lossy.
its working super thank for use full information if u have any documentation about this topic send links sir …
Sorry but I don’t have any documentation on how the jpg compression algorithm works. The basic idea behind the algorithm is out there; just google for it. I don’t know what version the NET Framework uses.
thanks sir
It adds blanks black space