Quickly convert an image to grayscale in C#


This example shows how you can quickly convert an image to grayscale by using the Bitmap32 class described in the post Use the Bitmap32 class to manipulate image pixels very quickly in C#. The ConvertBitmapToGrayscale method shown in the following code performs the conversion.

// Convert the Bitmap to grayscale.
private void ConvertBitmapToGrayscale(Bitmap bm, bool use_average)
    // Make a Bitmap24 object.
    Bitmap32 bm32 = new Bitmap32(bm);

    // Lock the bitmap.

    // Process the pixels.
    for (int x = 0; x < bm.Width; x++)
        for (int y = 0; y < bm.Height; y++)
            byte r = bm32.GetRed(x, y);
            byte g = bm32.GetGreen(x, y);
            byte b = bm32.GetBlue(x, y);
            byte gray = (use_average ?
                (byte)((r + g + b) / 3) :
                (byte)(0.3 * r + 0.5 * g + 0.2 * b));
            bm32.SetPixel(x, y, gray, gray, gray, 255);

    // Unlock the bitmap.

The code first makes a Bitmap32 object to manipulate the bitmap, and locks the object so it can start work.

The code then loops through the image’s pixels. If the use_average parameter is true, then the code makes the new pixel’s value be a simple average of the original pixel’s color components. If use_average is false, the method uses a weighted average. In many cases you won’t know the difference.

After it has processed the pixels, the code unlocks the Bitmap32 object.

The example program uses the method to display an average image (middle) and a weighted average image (right). That’s all there is to it!

Download Example   Follow me on Twitter   RSS feed   Donate

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

1 Response to Quickly convert an image to grayscale in C#

  1. Pingback: Use an ImageAttributes to convert an image to monochrome

Comments are closed.