Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...