在C#中更快地反转图像

taj*_*i01 3 .net c# colors picturebox invert

我正在使用WinForms.我的表格中有一个图片框.当我在图片框中打开图片时,我可以通过单击按钮来回反转颜色,但我的代码非常慢.我怎样才能提高性能.

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

        }

    }
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 11

每次更改像素时都会设置控件的图片,这会导致控件重绘自身.等到你完成图像:

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;
Run Code Online (Sandbox Code Playgroud)

  • `Get` /`SetPixel`非常慢.谷歌用于`LockBits`并使用它 - 你可以更快地获得数量级的结果. (4认同)