Am just breaking my head over this,
the problem is
to do pixel inversion of an image wen clicked using the button.
for example, if there is a bitmap image which reads 'A', then wen the button is clicked over it on run time, the background shud change to black and the letter A shud be inverted to white.

calling the bitmap image is on runtime.
and button click over it is also run time,
plz let me knw the button click event and the pixel inversion for this problem.

Thanks a lot...

7 Years
Discussion Span
Last Post by sknake

This is slow:

private void button1_Click(object sender, EventArgs e)
      Bitmap bmp = (Bitmap.FromFile(@"C:\letter.bmp") as Bitmap);
      pictureBox1.Image = bmp;

      Bitmap bmp2 = (bmp.Clone() as Bitmap);
      for (int x = 0; x < bmp.Width; x++)
        for (int y = 0; y < bmp.Height; y++)
          Color c = bmp2.GetPixel(x, y);
          Color inv = Color.FromArgb(c.A, 255 - c.R, 255 - c.G, 255 - c.B);
      pictureBox2.Image = bmp2;

You can also do it with unsafe{} operations. Take a look at:


Here is another way to do it:

Image img = Image.FromFile(fileName);
            Bitmap bmpInverted = new Bitmap(img.Width, img.Height);
            ImageAttributes ia = new ImageAttributes();
            ColorMatrix cmPicture = new ColorMatrix(new float[][]
                new float[] {-1, 0, 0, 0, 0},
                new float[] {0, -1, 0, 0, 0},
                new float[] {0, 0, -1, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {1, 1, 1, 0, 1}
            Graphics g = Graphics.FromImage(bmpInverted);
            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);

            // use the bmpInverted object, which contains the inverted bitmap
            pictureBox1.Image = bmpInverted;

I don't know how the speed compares to sknake's example, but he probably would know.;)

Votes + Comments
another good way to go about it

DdoubleD -- its faster. Anything (including a crayon) is faster than the method I posted. But its using all managed API calls which make some people feel better :P

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.