Title: Compress JPG files to a certain size in C#
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 the example to experiment with it and to see additional details.
|