Bashar Kokash' Blog

.Net Framework, windows and web development.

This site

Resources

Friends

Sponsors

  • MaximumASP
  • Packet Sniffer
    Home Loan
  • optimum rewards

Convert an image to gray scale

An image in a computer consists of three main color channels, they are RED, GREEN, and BLUE. So each pixle in an image has three values one for each channel ranging from 0 up 255. In order to get the gray scale of an image one channel should be used instead, and each pixle then will have only one value called the Gray level. To obtain the Gray level for a pixle 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 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;
}
Posted: Sep 24 2007, 02:08 AM by BasharKokash | with 3 comment(s)
Filed under:

Comments

Sudeep Jain said:

Thanks BasharKokash,

It was really helpful.

# October 19, 2007 5:25 AM

Phil said:

Here's an even better (and faster) way:

public static Bitmap ConvertImageToGrayscale(System.Drawing.Image original)

{

// create a blank bitmap the same size as original

Bitmap newBitmap = new Bitmap(original.Width, original.Height);

// get a graphics object from the new image

Graphics g = Graphics.FromImage(newBitmap);

// create the grayscale ColorMatrix

ColorMatrix colorMatrix = new ColorMatrix(new float[][]

 {

new float[] {.3f, .3f, .3f, 0, 0},

new float[] {.59f, .59f, .59f, 0, 0},

new float[] {.11f, .11f, .11f, 0, 0},

new float[] {0, 0, 0, 1, 0},

new float[] {0, 0, 0, 0, 1}

 });

// create some image attributes

ImageAttributes attributes = new ImageAttributes();

// set the color matrix attribute

attributes.SetColorMatrix(colorMatrix);

// draw the original image on the new image using the grayscale color matrix

g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

// dispose the Graphics object

g.Dispose();

return newBitmap;

}

# December 18, 2007 1:46 AM

BasharKokash said:

Thanks,

That's why I post may code, in order to learn from others.

# December 22, 2007 12:52 PM
The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.