Convert a directory’s files to grayscale in C#

[grayscale]

The example Quickly convert an image to grayscale in C# explains how to convert an image to grayscale. This program uses the same technique to convert all of the files in a directory to grayscale. (I needed this to prepare images for a newsletter that was being printed in grayscale.)

See the previous example for the basic technique. The following code shows the key new parts of this program.

// Convert the files in the selected directory.
private void ConvertFiles(string directory,
    bool use_average, bool include_subdirectories)
{
    Cursor = Cursors.WaitCursor;

    // Get the search option.
    SearchOption search_option;
    if (include_subdirectories)
    {
        search_option = SearchOption.AllDirectories;
    }
    else
    {
        search_option = SearchOption.TopDirectoryOnly;
    }

    // Look for graphic files.
    string[] patterns = { "*.png", "*.bmp", "*.jpg",
        "*.jpeg", "*.gif" };
    foreach (string pattern in patterns)
    {
        // Find the matching files.
        foreach (string filename in Directory.GetFiles(
            directory, pattern, search_option))
        {
            // Process the file.
            lblFilename.Text = filename;
            lblFilename.Refresh();
            ConvertFile(filename, use_average);
        }
    }

    Cursor = Cursors.Default;
    lblFilename.Text = "";
}

This code loops through a list of patterns to match image files: .png, .bmp, and so forth. For each pattern, the code uses Directory.GetFiles to get a list of the files matching the pattern. If you check the Include Subdirectories box, the program searches all of the selected directory’s subdirectories.

For each file found, the code calls the following ConvertFile method.

// Convert a file.
private void ConvertFile(string filename, bool use_average)
{
    // Load the file.
    using (Bitmap bm = LoadBitmapWithoutLocking(filename))
    {
        // Convert the image.
        ConvertBitmapToGrayscale(bm, use_average);

        // Save the file.
        SaveBitmapUsingExtension(bm, filename);
    }
}

This code calls LoadBitmapWithoutLocking to load the image file without locking it. It then calls the ConvertBitmapToGrayscale method and finally saves the file in the appropriate format depending on its extension. See these examples for details:

The program also has some other useful features such as letting the user click an ellipsis button to select the directory to process, and saving and restoring the selected directory when the program stops and starts. Download the example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




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

Leave a Reply

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