Fast Greyscale using unsafe code in C#
6
If anyone has tried using the .NET Graphics API, they know that replacing pixel colors takes a long time to complete. I did some research and found a good source. This code will adjust the color to greyscale by Binary.
The page is http://www.navicosoft.com/software_articles/softwares_articles_index.html for more information. It is under Basic Image Processing in the list of articles.
The page is http://www.navicosoft.com/software_articles/softwares_articles_index.html for more information. It is under Basic Image Processing in the list of articles.
/*Insert this as a function anywere, I used it in a seperate DLL to keep my form code clean. Just pass the Bitmap and the picture box to show it in to the function*/
public void greyscale(Bitmap bmp, PictureBox picBox)
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* imgPtr = (byte*)(data.Scan0);
byte red, green, blue;
for (int i = 0; i < data.Height; i++)
{
for (int j = 0; j < data.Width; j++)
{
blue = imgPtr[0];
green = imgPtr[1];
red = imgPtr[2];
imgPtr[0] = imgPtr[1] = imgPtr[2] =
(byte)(.299 * red
+ .587 * green
+ .114 * blue);
imgPtr += 3;
}
imgPtr += data.Stride - data.Width * 3;
}
}
bmp.UnlockBits(data);
picBox.Image = bmp;
}






There are currently no comments for this snippet.