In this example we will use simple color recalculation method to grayscale images. For each pixel on image we will calculate "average color" that we write back on image. Average color is sum of current color’s red, green and blue channels integer value divided by three. This value is assigned to all three channels for current pixel.
Colored picture of rabbit commiting
Although grayscaled she is still on action.
The cool thing about this rabbit is her colors – black, white and gray. As you can see rabbit colors are almost the same on both pictures. Okay, let’s see the code.
public Bitmap GrayScale(Bitmap Bmp)
for (int y = 0; y < Bmp.Height; y++)
for (int x = 0; x < Bmp.Width; x++)
c = Bmp.GetPixel(x, y);
rgb = (int)((c.R + c.G + c.B) / 3);
Bmp.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb));
Some notes about this code. It is also possible to calculate grayscale colors for channels differently. Instead of average of channels colors we can also use:
- maximum of channel values,
- minimum of channel values,
- custom divider.
It depends purely on context what one may need. Channel values maximum is good for pictures that are little bit too dark. Minimum is good for pictures that are little bit too bright. Custom divider may find usage in applications where user may want to change brightness manually. Current example by itself is goof for original pictures that are okay enough to publish them.
I know there are faster methods available for grayscaling. These methods are usually based on unmanaged code. This example here is slower but it is managed code you can use safely in your applications.