.net 在C#中更快地反转图像

4zcjmb1e  于 2023-05-08  发布在  .NET
关注(0)|答案(3)|浏览(133)

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

        }

    }
beq87vna

beq87vna1#

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

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(inv.A, (255 - inv.R), (255 - inv.G), (255 - inv.B));
        pic.SetPixel(x, y, inv);
    }
}
PictureBox1.Image = pic;
zhte4eai

zhte4eai2#

改进D Stanley的建议并避免将图像转换为Bitmap然后重新分配它的内存和处理过载,实际上可以直接获取和设置PictureBox的.Image上的像素,只需将其装箱并调用相关的Bitmap操作函数:

private void Button1_Click(object sender, System.EventArgs e) 
 {
    for (int y = 0; (y 
                <= (PictureBox1.Image.Height - 1)); y++) {
        for (int x = 0; (x 
                    <= (PictureBox1.Image.Width - 1)); x++) {
            Color inv = ((Bitmap)PictureBox1.Image).GetPixel(x, y);
            inv = Color.FromArgb(255, (255 - inv.R), (255 - inv.G), (255 - inv.B));
            ((Bitmap)PictureBox1.Image).SetPixel(x, y, inv);

        }

    }
}
hk8txs48

hk8txs483#

如果有人需要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)

相关问题