2
Color c1 = image.GetPixel (7, 400);
Color c2 = Color.Blue;
Console.WriteLine (image.GetPixel (7, 400));
Console.WriteLine (Color.Blue);
Console.WriteLine (c1.Equals(c2));

Console output:

Color [A=255, R=0, G=0, B=255]
Color [Blue]
False

I'm new to C# and I have NO idea why this is returning false. Can anyone please give me some insight as to why this doesn't work?

I'm trying to use it in this context.

for (int i = 0; i < image.Height; i++)  //loop through rows
            {
            for (int j = 0; j < image.Width; j++) //loop through columns
            {
                //Console.WriteLine ("i = " + i);
                //Console.WriteLine ("j = " + j);
                if ((image.GetPixel (i, j)) == Color.Blue) 
                {
                    return new Tuple<int, int>(i,j);
                }

                if (i == image.Height-1 && j == image.Width-1) 
                {
                    Console.WriteLine ("Image provided does not have a starting point. \n" +
                                                 "Starting points should be marked by Blue.");
                    Environment.Exit (0);
                }
            }
        }
xglide
  • 55
  • 1
  • 7

1 Answers1

5

As you already noted, the following example will return false:

Bitmap bmp = new Bitmap(1, 1);
bmp.SetPixel(0, 0, Color.Blue);
Color c1 = bmp.GetPixel(0, 0);
Console.WriteLine("GetPixel:" + c1);
Console.WriteLine("Color:" + Color.Blue);
Console.WriteLine("Equal?:" + c1.Equals(Color.Blue));

Console.ReadLine();

The reason is a little tricky to understand:

If you look at the source code of the Bitmap-Class, you will find

public Color GetPixel(int x, int y) { 
   //lot of other code     
   return Color.FromArgb(color); 
 } 

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CommonUI/System/Drawing/Bitmap@cs/1/Bitmap@cs

And the documentation for Color.Equals() says:

To compare colors based solely on their ARGB values, you should use the ToArgb method. This is because the Equals and Equality members determine equivalency using more than just the ARGB value of the colors. For example, Black and FromArgb(0,0,0) are not considered equal, since Black is a named color and FromArgb(0,0,0) is not.

https://msdn.microsoft.com/en-us/library/e03x8ct2(v=vs.110).aspx

so, the returned Color is not equal to Color.Blue - even if it is Color.Blue in terms of ARGB values.

To bypass this, use:

Console.WriteLine("Equal?:" + c1.ToArgb().Equals(Color.Blue.ToArgb()));

As last line of the example.

dognose
  • 20,360
  • 9
  • 61
  • 107