Pick a JPG compression level to make a file no bigger than a certain size in C#

The example View the tradeoff between compression level and file size in a JPG image 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 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 compressed 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 earlier example View the tradeoff between compression level and file size in a JPG image in C# for a description of the SaveJpg method.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.