簡體   English   中英

在 C# 中更快地反轉圖像

[英]Invert image faster in C#

我正在使用 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;
            }

        }

    }

每次更改像素時都會設置控件的圖片,這會導致控件重繪自身。 等到你完成圖像:

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;

如果有人需要 VB.NET 中的類似代碼。

還要注意變量 inv.A 而不是值 255。如果你的圖片框有透明度,你需要這個。

    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

用法:

    pic.image = InvertImageColors(pic.image)

它對我有用...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM