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

4.5
4
Phoenix Logan 186125 points

                                    for (int i = 0; i &lt; bmp.Width; i++)
{
    for (int j = 0; j &lt; 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));
    }
}

4.5 (4 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source