Comparing Bitmap Pixels to Colors

  • Thread starter Thread starter Typpo
  • Start date Start date
T

Typpo

Hi all,

I'm trying to compare a color returned by a Bitmap's GetPixel method to
a normal static color of the Color class. My problem: after setting a
pixel to a certain color, the color returned by GetPixel isn't
considered the same color anymore. Example code:

bmp.SetPixel(0, 0, Color.Blue);
Color cc = bmp.GetPixel(0, 0);

if (cc.Equals(Color.Blue))
{
MessageBox.Show("Pixel is blue");
}
else
{
MessageBox.Show("Pixel isn't blue");
}

....this program will always tell me that the pixel isn't blue. Is there
anything I'm doing wrong? What's the proper way to compare these colors?

Thanks in advance.
 
The compare routine looks at other properties such as the KnownColor flag to
verify equality. The only way to check is to see if the R, G, B and, if
needed, A values match.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Bob said:
The compare routine looks at other properties such as the KnownColor flag to
verify equality. The only way to check is to see if the R, G, B and, if
needed, A values match.

Thanks. The following method works for me.

private bool IsSameColor(Color first, Color second)
{
if (first.A.Equals(second.A)
&& first.R.Equals(second.R)
&& first.G.Equals(second.G)
&& first.B.Equals(second.B))
return true;
else
return false;
}
 
For speed optimization I would check Alpha last as most likely it is the
same in all pixels :)
 
Back
Top