Invert image faster in C#

点点圈 提交于 2019-12-18 07:04:14

问题


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

        }

    }

回答1:


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;



回答2:


It`s work for me...

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


来源:https://stackoverflow.com/questions/33024881/invert-image-faster-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!