Compress all of the JPG files in a directory in C#

Over the years I've collected hundreds of pictures of family, friends, school plays, and baseball games. Unfortunately they come off the camera really huge with little JPG compression so they take up a lot of space. Often reducing the compression level a little produces an image that still looks good on the computer but that takes up much less space.

The example Use a binary search to quickly pick a JPG compression level in C# shows how to adjust JPG file compression to save space. This example applies that method to all of the files in a directory. The following code shows the key loop used by this example.
// Loop through the directory's JPEGs.
string dir_name = txtFolder.Text;
foreach (string file_name in Directory.GetFiles(dir_name, "*.jp*g"))
{
    // Process this file.
    try
    {
        // Update the original size.
        long file_size = new FileInfo(file_name).Length;
        original_size += file_size;
        txtOriginalTotalSize.Text = original_size.ToFileSizeApi();

        if (set_level)
        {
            // Save the file at the desired level.
            using (Bitmap bm = ImageStuff.LoadBitmap(file_name))
            {
                ImageStuff.SaveJpg(bm, file_name, level);
            }
        }
        else
        {
            // Save the file with no more than the desired size.
            if (file_size > max_size)
            {
                using (Bitmap bm = ImageStuff.LoadBitmap(file_name))
                {
                    ImageStuff.SaveJpgAtFileSize(bm, file_name, max_size);
                }
            }
        }

        // Update the final size.
        final_size += new FileInfo(file_name).Length;
        txtFinalTotalSize.Text = final_size.ToFileSizeApi();
        num_files++;
        txtFilesProcessed.Text = num_files.ToString();

        txtFilesProcessed.Refresh();
        txtOriginalTotalSize.Refresh();
        txtFinalTotalSize.Refresh();

        if (num_files % 10 == 0) Application.DoEvents();
    }
    catch (Exception ex)
    {
        // Display the error message and give the user a chance to stop.
        if (MessageBox.Show("Error compressing file " +
            file_name + "\n" + ex.Message + "\nDo you want to continue?",
            "Error", MessageBoxButtons.YesNo,
            MessageBoxIcon.Error) == DialogResult.No)
        {
            break;
        }
    }
}

The code uses Directory.GetFiles to get an array holding the files that end with .jpg or .jpeg. For each file, the program either calls SaveJpg or SaveJpgAtFileSize to save the file with a new compression level or at a new maximum size, depending on whether you select the Set Compression Level radio button.

Note that the code doesn't open the file if the Set Max File Size radio button is selected and the file's size is already small enough. That saves a fair amount of time. It also prevents the program from re-saving the file if it doesn't need to, which may reduce the file's quality for no good reason.

Download the example to see the rest of the code.

   

 

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.