Check if the image is tinted or not.

I am trying to figure out if the image is tinted or not. There is an answer in this StackOverflow question that says I have to check the enum PixelFormat Image. Unfortunately, the answer is not very clear to me. Is it possible to check whether it differs image.PixelFormatfrom PixelFormat.Format16bppGrayScalethat it is a color image? What about other enum values? The MSDN documentation is not very clear ...

+3
source share
1 answer

You can improve this by avoiding Color.FromArgb and iterating over bytes instead of ints, but I thought it would be more readable to you and more understandable as an approach.

, (32bpp ARGB), , - .

, GetPixel, .

alpha 0, , , GrayScale, 0 , . - R = G = B, ( = 255, ).

private static unsafe bool IsGrayScale(Image image)
{
    using (var bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
    {
        using (var g = Graphics.FromImage(bmp))
        {
            g.DrawImage(image, 0, 0);
        }

        var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);

        var pt = (int*)data.Scan0;
        var res = true;

        for (var i = 0; i < data.Height * data.Width; i++)
        {
            var color = Color.FromArgb(pt[i]);

            if (color.A != 0 && (color.R != color.G || color.G != color.B))
            {
                res = false;
                break;
            }
        }

        bmp.UnlockBits(data);

        return res;
    }
}
+11

All Articles