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