2015-10-08 39 views
2

我正在使用WinForms。我的表格中有一个图片框。当我在图片框中打开图片时,只需点击一个按钮即可反转颜色,但我的代码非常慢。我该如何提高性能。在C中快速反转图像#

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

     } 

    } 

回答

7

您每次更改像素时都会设置控件的图片,这会导致控件重新绘制自己。等到你已经完成了图像:

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; 
+0

@D士丹利感谢您的解释,并给予一个例子。它像一个魅力。 – taji01

+3

'Get' /'SetPixel'非常慢。谷歌的'LockBits'并使用它 - 你可以得到更快的结果数量级。 –

+0

@LucasTrzesniewski我会研究一下。在这种情况下,我不太熟悉如何使用LockBits。如果你能举一个例子,我会很感激。 – taji01

-2

它`为我工作...

 private Image InvertingImage(Image source) 
    { 
     //create a blank bitmap the same size as original 
     Bitmap newBitmap = new Bitmap(source.Width, source.Height); 

     //get a graphics object from the new image 
     Graphics g = Graphics.FromImage(newBitmap); 

     // create the negative color matrix 
     ColorMatrix colorMatrix = 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} 
}); 

     // create some image attributes 
     ImageAttributes attributes = new ImageAttributes(); 

     attributes.SetColorMatrix(colorMatrix); 

     g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 
        0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); 

     //dispose the Graphics object 
     g.Dispose(); 

     return newBitmap; 
    } 
+0

此代码似乎与[本答案](http://stackoverflow.com/a/11781561/1364007)(包括注释)中的代码**相同**,本身已被复制(带有归属) [这里](http://mariusbancila.ro/blog/2009/11/13/using-colormatrix-for-creating-negative-image/)。如果您从其他地方复制它,则应该将原始属性归类以避免[抄袭](http://meta.stackoverflow.com/q/251389/1364007)。 –