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;
}
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