Search code examples
c#.netcolorspicturebox

Invert image faster in C#


I'm using WinForms. I have a picture-box in my form. When I open a picture in the picture-box I am able to invert the colors back and forth on a click of a button, but my code is extremely slow. How can I increase the performance.

   private void Button1_Click(object sender, System.EventArgs e) 
     {
        Bitmap pic = new Bitmap(PictureBox1.Image);
        for (int y = 0; (y 
                    <= (pic.Height - 1)); y++) {
            for (int x = 0; (x 
                        <= (pic.Width - 1)); x++) {
                Color inv = pic.GetPixel(x, y);
                inv = Color.FromArgb(255, (255 - inv.R), (255 - inv.G), (255 - inv.B));
                pic.SetPixel(x, y, inv);
                PictureBox1.Image = pic;
            }

        }

    }

Solution

  • You are setting the control's picture each time you change a pixel, which causes the control to redraw itself. Wait until you've finished the image:

    Bitmap pic = new Bitmap(PictureBox1.Image);
    for (int y = 0; (y <= (pic.Height - 1)); y++) {
        for (int x = 0; (x <= (pic.Width - 1)); x++) {
            Color inv = pic.GetPixel(x, y);
            inv = Color.FromArgb(inv.A, (255 - inv.R), (255 - inv.G), (255 - inv.B));
            pic.SetPixel(x, y, inv);
        }
    }
    PictureBox1.Image = pic;