如何确定位图是亮的还是暗的

本文关键字:何确定 位图 | 更新日期: 2023-09-27 18:36:35

我想找出位图是相当明亮还是相当黑暗。我意识到"相当明亮或黑暗"不是一个非常精确的定义,但我只需要想出一些非常简单的东西。

我的想法是将位图转换为单色位图,然后将白色像素的数量与黑色像素的数量进行比较。

这是我的 C# 代码:

private bool IsDark(Bitmap bitmap)
    {
        if (bitmap == null)
            return true;
        var countWhite = 0;
        var countBlack = 0;
        // Convert bitmap to black and white (monchrome)
        var bwBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format1bppIndexed);
        for (int x = 0; x < bwBitmap.Width - 1; x++)
        {
            for (int y = 0; y < bwBitmap.Height - 1; y++)
            {
                var color = bwBitmap.GetPixel(x, y);
                if (color.A == 255)
                    countWhite++;
                else
                    countBlack++;
            }
        }
        return countBlack > countWhite;
    }

我不明白的是:黑色像素的数量始终为 0 - 无论我使用什么位图。

我错过了什么?

另外:我很确定有更有效的方法来解决这个任务。但是在这一点上,我只想了解为什么上面的代码失败了......

谢谢大家!英格玛

如何确定位图是亮的还是暗的

首先,您可以尝试如下内容:

if (color.R == 0 && color.G == 0 && color.B == 0)
{
    // black
    countBlack++;
}
else if (color.R == 255 && color.G == 255 && color.B == 255)
{
    // white
    countWhite++;
}
else
{
    // neither black or white
}

作为旁注GetPixel(x, y)很慢,看看Bitmap.LockBits。