Quickly convert an image to grayscale in C#

private void ConvertBitmapToGrayscale(Bitmap bm, bool use_average)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.
{
// 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();
}


-->
Comments