如何从位图设置和检索像素

时间:2013-12-04 20:00:53

标签: c# bitmap

为什么以下条件失败?

brush = new Bitmap(10, 10);
brush.SetPixel(1, 1, Color.Black);
if (brush.GetPixel(1, 1) == Color.Black)
{          
    MessageBox.Show("hello");
}

// Will not show "hello"

2 个答案:

答案 0 :(得分:3)

您的像素确实是黑色,但似乎失败了,因为Color.BlackKnownColorNamedColor,而ff000000(GetPixel的结果)则不然。您可以更改条件以直接验证ARGB值:

if (brush.GetPixel(1, 1).ToArgb() == Color.Black.ToArgb())
{          
    MessageBox.Show("hello");
}

答案 1 :(得分:0)

==运算符具有以下定义:

public static bool operator ==(Color left, Color right)
{
  if (left.value != right.value || (int) left.state != (int) right.state || (int) left.knownColor != (int) right.knownColor)
    return false;
  if (left.name == right.name)
    return true;
  if (left.name == null || right.name == null)
    return false;
  else
    return left.name.Equals(right.name);
}

如果您在调试模式下查看Color.Blackresult from GetPixel,您会看到不同之处。