0

Please dont quote this How can I check the color depth of a Bitmap? or How to check if a picture is in grayScale

Because an image can be 24/32 bit per pixel even if all unique colors are grey scale or less than 256 and each pixel can be 24 or 32 bit.

How do I find that the pixel in an image Bitmap.GetPixel(x, y) has equal R,G,B vales so that I can find out if all pixels in an image lie in grey scale range. Because the R,G,B value of a grey scale pixel is same. Or is there any better way to find if the image is in grey scale?

I am writing a code to compress the size of a 16/24/32 bit image such that if the image has 256 unique colors then change it to 8 bit image and save it.

First I count unique colors in an image that has higher than 8 its per pixel.

If the unique colors in the image are less than or equal to 256 then

  1. If all the unique colors are in greyscale range then convert it to greyscale
  2. Otherwise if any color is not greyscale then convert image to 8 BPP

uint UniqueColors(Bitmap Bitmap)
{
    try
    {
        List<int> lstColors = new List<int>();

        if (null == Bitmap)
            return 0;

        for (int iCount = 0; iCount < Bitmap.Height; iCount++)
            for (int iCounter = 0; iCounter < Bitmap.Width; iCounter++)
                if (!lstColors.Contains(Bitmap.GetPixel(iCounter, iCount).ToArgb()))
                    lstColors.Add(Bitmap.GetPixel(iCounter, iCount).ToArgb());

        Bitmap.Dispose();

        return Convert.ToUInt32(lstColors.Count);
    }
    catch (Exception)
    {
        Bitmap.Dispose();
        return 0;
    }
}

And then:

if (256 >= UniqueColors(new Bitmap(string ImagePath)))
{
    if (Is_Greyscale(new Bitmap(ImagePath))
        Convert_To_Greyscale(ImagePath);
    else
        Convert_To_8Bits(ImagePath);
}

now I am stuck how do I find if each unique color in the image lies in the greyscae rage. By which I mean that each unique color has equal (R, G, B) values. Like R=G=B. How can I find it in my code line

Bitmap.GetPixel(iCounter, iCount).ToArgb()
Community
  • 1
  • 1
Computer User
  • 2,839
  • 4
  • 47
  • 69
  • First: GetPixel is slow. So having it twice in your inner loop is not a good idea. For real speed look into LockBits. Second: to check a `Color c = bmp.GetPixel(x,y);` simply do `bool isGrey = (c.R == c.G) && (c.G ==c.B);` – TaW Apr 02 '16 at 15:07

1 Answers1

2

Bitmap.GetPixel() returns a Color structure which has fields R, G and B so you can just compare them however you want.

Do note that using GetPixel() is very slow, but if you don't need speed it will do.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • thanks, I was so frustrated that everywhere on internet people are suggesting Image.PixelFormat which will give wrong result. because an image can have 256 unique colors but each color can be 24 bits. So, image can be reduced to 8 bits per pixel. – Computer User Apr 02 '16 at 15:11