Quickly convert an image to grayscale in C#

The example Manipulate 32-bit image pixels using a class with simple pixel get and set methods in C# explains how to use a class to quickly manipulate the pixels in an image. This example uses the same class to convert an image into grayscale in one of two ways. The ConvertBitmapToGrayscale method shown in the following code performs the conversion.
private void ConvertBitmapToGrayscale(Bitmap bm, bool use_average)
{
// Make a Bitmap24 object.
Bitmap32 bm32 = new Bitmap32(bm);

// Lock the bitmap.
bm32.LockBitmap();

// 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.
bm32.UnlockBitmap();
}

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.


-->