检查,如果图像是彩色或不 [英] Check If Image Is Colored Or Not

查看:179
本文介绍了检查,如果图像是彩色或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚的图像是彩色的还是不行。在<一个href="http://stackoverflow.com/questions/2150504/how-can-i-check-the-color-depth-of-a-bitmap">this StackOverflow的问题,有回复,说我应该检查图像的的PixelFormat 枚举。不幸的是,得到的答复不是很清楚,我。是否安全,检查是否 image.PixelFormat 不同于 PixelFormat.Format16bppGrayScale 来考虑,这是一个彩色图像?那么枚举的其他值? MSDN文档不是很清楚......

I'm trying to figure out whether an image is colored or not. On this StackOverflow question, there's a reply that says that I should check the PixelFormat enum of the Image. Unfortunately, the reply isn't very clear to me. Is it safe to check whether the image.PixelFormat is different from PixelFormat.Format16bppGrayScale to consider that it is a colored image? What about the other values of the enumeration? The MSDN documentation isn't very clear...

推荐答案

您可以通过避免Color.FromArgb,并遍历字节,而不是整数改善这一点,但我认为这将是更具可读性的你,更容易理解作为一种方法。

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

的总体思路是绘制图像为已知格式的位图(32bpp的ARGB), 然后检查位图是否包含任何颜色。

The general idea is draw the image into a bitmap of known format (32bpp ARGB), and then check whether that bitmap contains any colors.

锁定位图的位,您可以通过它的色彩数据多次迭代比使用getPixel速度更快,使用不安全code。

Locking the bitmap's bits allows you to iterate through it's color-data many times faster than using GetPixel, using unsafe code.

如果一个像素的Alpha值为0,那么它显然是灰度,因为阿尔法0意味着它是完全不透明。除此之外 - 。当R = G = B,那么它是灰色(如果他们= 255,它是黑色)

If a pixel's alpha is 0, then it is obviously GrayScale, because alpha 0 means it's completely opaque. Other than that - if R = G = B, then it is gray (and if they = 255, it is black).

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;
    }
}

这篇关于检查,如果图像是彩色或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆