Compress JPG files to a certain size in C#

[compress JPG files]

The example Optimize JPEG compression level and file size in C# shows how to save a JPG file with different compression levels. Using a smaller level makes the resulting file smaller but introduces more error into the image.

If you set a maximum file size and click Go, this program picks a compression level that makes the file no bigger than that size. The following code saves an image at no more than the indicated size, if that’s possible.

// Save the file with the indicated maximum file size.
// Return the compression level used.
public static int SaveJpgAtFileSize(Image image,
    string file_name, long max_size)
    for (int level = 100; level > 5; level -= 5)
        // Try saving at this compression level.                
        SaveJpg(image, file_name, level);

        // If the file is small enough, we're done.
        if (GetFileSize(file_name) <= max_size) return level;

    // Stay with level 5.
    return 5;

This code simply tries decreasing compression levels starting with 100 until it finds one that compresses the file enough to fit within the allowed size.

The following GetFileSize helper method simply returns a file’s size.

// Return the file's size.
public static long GetFileSize(string file_name)
    return new FileInfo(file_name).Length;

See the previous example for a description of the SaveJpg method.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, files, graphics, image processing and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Compress JPG files to a certain size in C#

  1. Pingback: Quickly pick JPG compression level in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *