Convert an image to grayscale

This post explains the basics of pixels and colors, and how to use a simple formula to convert an image to grayscale in C#.

An image in a computer consists of three primary color channels; they are RED, GREEN, and BLUE. So each pixel in an image has three values, one for each channel ranging from 0 up 255. To get the grayscale of an image, one channel should be used instead, and each pixel then will have only one value called the Gray level. To obtain the Gray level for a pixel of an image, we should use the following formula:

Gray = 0.3 * RED + 0.6 * GREEN + 0.1 * BLUE

This method applies the previous formula on the pixels of a given image resulting in the gray level of the image.

public Image ToGrayScale(Image im)
 {
   int R, G, B, Gray;
 // create a Bitmap Object to access pixels.
   Bitmap Bm = new Bitmap(im);
   for (int i = 0; i < Bm.Size.Height; i++)
   {
      for (int j = 0; j < Bm.Size.Width; j++)
      {
       // for each pixel get the the channel colors
       R = Bm.GetPixel(j, i).R;
       G = Bm.GetPixel(j, i).G;
       B = Bm.GetPixel(j, i).B;
       // Apply the formula
       Gray = (int)(0.3 * R) + (int)(0.6 * G) + (int)(0.1 * B);
       Bm.SetPixel(j, i, Color.FromArgb(Gray, Gray, Gray));
      }
   }
   return Bm;
 }