Invert image faster in C#

14,223

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(255, (255 - inv.R), (255 - inv.G), (255 - inv.B));
        pic.SetPixel(x, y, inv);
    }
}
PictureBox1.Image = pic;
Share:
14,223
taji01
Author by

taji01

Updated on June 04, 2022

Comments

  • taji01
    taji01 almost 2 years

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