Search code examples
c#bitmapsystem.drawing

How do I check whether a Bitmap pixel is touching another Color? (C#)


I'm attempting to check if a pixel in a bitmap is touching another pixel of a certain color but I'm not quite sure how to do it.

So far, I can iterate through the pixels like this:

            for (int x = 0; i < bitmap.Width; ++x)
            {
                for (int y = 0; h < bitmap.Height; ++y)
                {
                    // check if this pixel is touching Color.Blue
                }
            }

If anyone knows how to do this and could tell me, I'd appreciate it. Thanks in advance.

I tried doing image.GetPixel(x - 1, y) == Color.Blue as a test on the left direction, but it just returned false every time.


Solution

  • Of course it will return false. Few are the pixels that are set to a basic color (red, green, blue, etc. — not something like "beige"). Colors are usually mixed to make them more pleasing to the eye. If a pixel is set to an RGB color (45, 45, 255) — you will see blue, eye-pleasing pixel, but it won't be equal to Color.Blue.

    I advise you to check closeness to blue, not equality. Try something like this (it tests on the left direction):

    Color color = bitmap.GetPixel(x - 1, y);
    
    if (color.B >= 150 && color.R <= 50 && color.G <= 50) {
        // The pixel is touching a color close to blue, do something
    }