Convert all of the image files in a directory to grayscale in C#

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)
{
this.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);
}
}

this.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 check box, the program searches all of the selected directory's subdirectories.

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

// 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.

  

 

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.