Paul Maddox

Software development team leader specialising in Microsoft Visual C# and C++ from the Northwest of England. Experience working in a globalised business and team; understanding of enterprise business operation and practices; experience reporting to executive management Skills in numerous languages and technologies; knowledge of formal software development lifecycle; experience of architecture design

Monday, November 17, 2008

Convert C# .NET Bitmap to grayscale

Here's some code to convert a Bitmap into grayscale using luminance. Note, this does not change the color depth, rather it sets the pixels to grey within a 24bit color space.

private static Bitmap ToGrayscale(Bitmap bmIn)
{
 Bitmap bmOut = new Bitmap(bmIn.Width, bmIn.Height, PixelFormat.Format24bppRgb);

 for (int x = 0; x < bmIn.Width; x++)
 {
  for (int y = 0; y < bmIn.Height; y++)
  {
   Color px = bmIn.GetPixel(x, y);

   int luminance = (int)((0.3f * px.R) + (0.59 * px.G) + (0.11 * px.B));

   bmOut.SetPixel(x, y, Color.FromArgb(luminance, luminance, luminance));
  }
 }

 return bmOut;
}

0 Comments:

Post a Comment

<< Home