Compress JPG files in a directory in C#

[compress JPG files]

I wrote this example to help produce reduced-size versions of some of the thousands of pictures I’ve collected over the years. Unfortunately pictures you take with a modern camera or phone tend to be enormous. Fortunately most of my relatives and Facebook friends don’t usually need to see the images at their original fidelity. Usually you can reduce the compression level a little to compress JPG files and produce an image that still looks good on the computer but that takes up much less space.

The example Quickly pick JPG compression level in C# shows how to adjust JPG file compression to save space. This example applies that method to compress JPG 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.
        // 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);
            // Save the file with no more than the desired size.
            if (file_size > max_size)
                using (Bitmap bm = ImageStuff.LoadBitmap(file_name))
                        bm, file_name, max_size);

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


        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)

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.

Download the example to see the rest of the code.

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.

Also note that the program overwrites the initial files, so after you run the program you can no longer access the files with their original fidelity. If you want to keep the original files, make copies and then compress the copies.

Download Example   Follow me on Twitter   RSS feed   Donate

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

Leave a Reply

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