lockbits method code example
Example 1: lockbits method
//Lock bitmap's bits to system memory
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
//Scan for the first line
IntPtr ptr = bmpData.Scan0;
//Declare an array in which your RGB values will be stored
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
//Copy RGB values in that array
Marshal.Copy(ptr, rgbValues, 0, bytes);
for (int i = 0; i < rgbValues.Length; i += 3)
{
//Set RGB values in a Array where all RGB values are stored
byte gray = (byte)(rgbValues[i] * .21 + rgbValues[i + 1] * .71 + rgbValues[i + 2] * .071);
rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = gray;
}
//Copy changed RGB values back to bitmap
Marshal.Copy(rgbValues, 0, ptr, bytes);
//Unlock the bits
bmp.UnlockBits(bmpData);
Example 2: lockbits method
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color c = bmp.GetPixel(i, j);
//Apply conversion equation
byte gray = (byte)(.21 * c.R + .71 * c.G + .071 * c.B);
//Set the color of this pixel
bmp.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
}
}