Invert image faster in C#

后端 未结 3 1656
醉酒成梦
醉酒成梦 2020-12-19 19:57

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 c

相关标签:
3条回答
  • 2020-12-19 20:02

    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;
    
    0 讨论(0)
  • 2020-12-19 20:23

    In case someone need the similar code in VB.NET.

    Also note the variable inv.A instead of the value 255. In case your picturebox has transparency you need this.

        Public Function InvertImageColors(ByVal p As Image) As Image
            Dim pic As New Bitmap(p)
            For y As Integer = 0 To pic.Height - 1
                For x As Integer = 0 To pic.Width - 1
                    Dim inv As Color = pic.GetPixel(x, y)
                    inv = Color.FromArgb(inv.A, 255 - inv.R, 255 - inv.G, 255 - inv.B)
                    pic.SetPixel(x, y, inv)
                Next x
            Next y
            Return pic
        End Function
    

    Usage:

        pic.image = InvertImageColors(pic.image)
    
    0 讨论(0)
  • 2020-12-19 20:25

    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;
        }
    
    0 讨论(0)
提交回复
热议问题