【问题标题】:Determine if Alpha Channel is Used in an Image确定图像中是否使用了 Alpha 通道
【发布时间】:2010-06-17 19:16:47
【问题描述】:

当我将图像引入我的程序时,我想确定是否:

  1. 他们有一个 alpha 通道
  2. 如果使用了 alpha 通道

#1 使用Image.IsAlphaPixelFormat 非常简单。但是,对于 #2,除了循环遍历每个像素之外,是否有一种简单的方法可以确定是否至少有一个像素具有使用的 alpha 通道(即设置为其他值255)?我只需要返回一个布尔值,然后我将确定是将其保存为 32 位还是 24 位。

更新:我发现ImageFlags.HasTranslucent 应该为我提供我正在寻找的东西 - 不幸的是,它根本不起作用。例如,具有至少 66 个 alpha 通道(半透明)的像素格式的 PNG 继续报告 False(用法:if((img.Flags & ImageFlags.HasTranslucent) == 4) ...;)。我已经对所有类型的图像进行了测试,包括 alpha 值 >0 和 False。任何人都使用过它并知道它是否可以在 GDI+ 中使用?

【问题讨论】:

  • 您已链接到本地​​帮助副本,而不是在线版本。
  • 帮助说明“指定像素数据的 alpha 值不是 0(透明)和 255(不透明)。”这不是您想要的,因为您也想用 0 表示 true。
  • 很奇怪,我没有本地的帮助副本。无论如何,是的,HasTranslucent 会让我走得很远,但不是 100%,因为我仍然需要 0 值。

标签: c# .net gdi+ transparency system.drawing.imaging


【解决方案1】:

您不必遍历每个像素(当然可以,但这取决于图像)。设置为循环遍历所有像素,但当您找到 255 以外的 alpha 值时,只需跳出循环,请使用以下伪代码:

bool hasAlpha = false;
foreach (var pixel in image)
{
    hasAlpha = pixel.Alpha != 255;
    if (hasAlpha)
    {
        break;
    }
}

您只需检查没有任何 Alpha 的图像的所有像素。对于确实有 alpha 的图像,这将很快爆发。

【讨论】:

  • 感谢 ChrisF。这似乎是做到这一点的唯一方法。我会让这个问题再多站一会,看看是否有其他解决方案。
  • @Otaku - 我很想看看是否还有其他方法。
  • 天哪,这似乎是唯一的方法。我希望有一些更简单的东西,但是......
  • 一点说明:我前段时间有这个任务(检查是否实际使用了alpha通道),所以我想说你应该考虑为你的循环使用不安全的代码。跨度>
  • 确定图像是否不透明后,可以将结果保存到标志中。只要图像保持未修改,您就可以检查该标志而不是重新检查图像。
【解决方案2】:

你找不到比这更好的解决方案了,我花了好几个小时来优化:

public bool IsAlphaBitmap(ref System.Drawing.Imaging.BitmapData BmpData)
{
    byte[] Bytes = new byte[BmpData.Height * BmpData.Stride];
    Marshal.Copy(BmpData.Scan0, Bytes, 0, Bytes.Length);
    for (p = 3; p < Bytes.Length; p += 4) {
        if (Bytes[p] != 255) return true;
    }
    return false;
}

【讨论】:

  • 小心点。您必须检查每像素的位数才能正确执行此操作。这仅适用于 32 bpp 图像。
  • 唯一可能比这更快的是通过unsafe和指针直接遍历内存而不复制。
  • @IllidanS4 当然可以,在实践中这是要走的路。
【解决方案3】:

自从发布my first answer here 以来,我发现LockBits 命令实际上可以将图像数据转换 为所需的像素格式。这意味着,无论输入如何,您都可以简单地将字节“作为”每像素 32 位 ARGB 数据进行检查。由于该格式具有 4 字节像素,并且 .Net 框架中的步幅为 always a multiple of 4 bytes,因此通常非常正确调整数据读取以适应扫描线长度的重要问题变得无关紧要。这一切都大大简化了代码。

当然,我的另一个答案中的前两项检查仍然适用;在切换到完整数据扫描之前,检查位图标志上的HasAlpha 标志和索引格式的调色板条目上的 alpha 是确定图像可以是否具有透明度的一种非常快速的初始方法。

我还发现,带有 alpha 功能调色板的索引 png 实际上是一回事(尽管 poorly supported in .Net),所以只检查索引格式上的单一 alpha 功能颜色太天真了。

考虑到所有这些,以及将调色板检查变为单行的 linq 操作,最终调整后的代码变为:

public static Boolean HasTransparency(Bitmap bitmap)
{
    // Not an alpha-capable color format. Note that GDI+ indexed images are alpha-capable on the palette.
    if (((ImageFlags)bitmap.Flags & ImageFlags.HasAlpha) == 0)
        return false;
    // Indexed format, and no alpha colours in the image's palette: immediate pass.
    if ((bitmap.PixelFormat & PixelFormat.Indexed) != 0 && bitmap.Palette.Entries.All(c => c.A == 255))
        return false;
    // Get the byte data 'as 32-bit ARGB'. This offers a converted version of the image data without modifying the original image.
    BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
    Int32 len = bitmap.Height * data.Stride;
    Byte[] bytes = new Byte[len];
    Marshal.Copy(data.Scan0, bytes, 0, len);
    bitmap.UnlockBits(data);
    // Check the alpha bytes in the data. Since the data is little-endian, the actual byte order is [BB GG RR AA]
    for (Int32 i = 3; i < len; i += 4)
        if (bytes[i] != 255)
            return true;
    return false;
}

这适用于任何输入像素格式,无论是否调色。

【讨论】:

  • 很好的答案!谢谢!
  • 调色板检查是个好主意...
【解决方案4】:

为不同类型的图像组合一堆方法让我得到了最后一种方法,它似乎对你转储到其中的任何图像都做得很好,无论是潜在的透明 gif 还是包含 alpha 通道的 png。感谢 Elmo 对快速字节读取方法的回答。

附注:不要使用Image.IsAlphaPixelFormat(bitmap.PixelFormat)):它认为索引(调色板)格式不支持alpha,而这些图像可以实际上拥有alpha。只是,不是每个像素,而是每个调色板条目。不过,此类启用 alpha 的 8 位图像确实启用了 HasAlpha 标志,因此这仍然是一个有用的检查。

[[注意:我已经大大简化了这个逻辑。见我的other answer.]]

public static Boolean HasTransparency(Bitmap bitmap)
{
    // not an alpha-capable color format.
    if ((bitmap.Flags & (Int32)ImageFlags.HasAlpha) == 0)
        return false;
    // Indexed formats. Special case because one index on their palette is configured as THE transparent color.
    if (bitmap.PixelFormat == PixelFormat.Format8bppIndexed || bitmap.PixelFormat == PixelFormat.Format4bppIndexed)
    {
        ColorPalette pal = bitmap.Palette;
        // Find the transparent index on the palette.
        Int32 transCol = -1;
        for (int i = 0; i < pal.Entries.Length; i++)
        {
            Color col = pal.Entries[i];
            if (col.A != 255)
            {
                // Color palettes should only have one index acting as transparency. Not sure if there's a better way of getting it...
                transCol = i;
                break;
            }
        }
        // none of the entries in the palette have transparency information.
        if (transCol == -1)
            return false;
        // Check pixels for existence of the transparent index.
        Int32 colDepth = Image.GetPixelFormatSize(bitmap.PixelFormat);
        BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
        Int32 stride = data.Stride;
        Byte[] bytes = new Byte[bitmap.Height * stride];
        Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
        bitmap.UnlockBits(data);
        if (colDepth == 8)
        {
            // Last line index.
            Int32 lineMax = bitmap.Width - 1;
            for (Int32 i = 0; i < bytes.Length; i++)
            {
                // Last position to process.
                Int32 linepos = i % stride;
                // Passed last image byte of the line. Abort and go on with loop.
                if (linepos > lineMax)
                    continue;
                Byte b = bytes[i];
                if (b == transCol)
                    return true;
            }
        }
        else if (colDepth == 4)
        {
            // line size in bytes. 1-indexed for the moment.
            Int32 lineMax = bitmap.Width / 2;
            // Check if end of line ends on half a byte.
            Boolean halfByte = bitmap.Width % 2 != 0;
            // If it ends on half a byte, one more needs to be processed.
            // We subtract in the other case instead, to make it 0-indexed right away.
            if (!halfByte)
                lineMax--;
            for (Int32 i = 0; i < bytes.Length; i++)
            {
                // Last position to process.
                Int32 linepos = i % stride;
                // Passed last image byte of the line. Abort and go on with loop.
                if (linepos > lineMax)
                    continue;
                Byte b = bytes[i];
                if ((b & 0x0F) == transCol)
                    return true;
                if (halfByte && linepos == lineMax) // reached last byte of the line. If only half a byte to check on that, abort and go on with loop.
                    continue;
                if (((b & 0xF0) >> 4) == transCol)
                    return true;
            }
        }
        return false;
    }
    if (bitmap.PixelFormat == PixelFormat.Format32bppArgb || bitmap.PixelFormat == PixelFormat.Format32bppPArgb)
    {
        BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
        Byte[] bytes = new Byte[bitmap.Height * data.Stride];
        Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
        bitmap.UnlockBits(data);
        for (Int32 p = 3; p < bytes.Length; p += 4)
        {
            if (bytes[p] != 255)
                return true;
        }
        return false;
    }
    // Final "screw it all" method. This is pretty slow, but it won't ever be used, unless you
    // encounter some really esoteric types not handled above, like 16bppArgb1555 and 64bppArgb.
    for (Int32 i = 0; i < bitmap.Width; i++)
    {
        for (Int32 j = 0; j < bitmap.Height; j++)
        {
            if (bitmap.GetPixel(i, j).A != 255)
                return true;
        }
    }
    return false;
}

【讨论】:

  • 哎呀,修复了调色板图像行位置计算中的错误。
  • 我有很多照片的 trans 位设置为 254。所以将该行从 if (col.A != 255) 更改为 if (col.A &lt; 254)
  • 哇,太糟糕了。为什么人们会使用几乎不透明?
  • @mikenelson 注意,我刚刚添加了另一个答案,大大简化了这个逻辑;发帖一段时间后,我发现LockBits 实际上可以将图像数据转换 为其他像素格式,这简化了很多事情。
【解决方案5】:

我得到了一个更高级的解决方案,基于 ChrisF 的回答:

public bool IsImageTransparent(Bitmap image,string optionalBgColorGhost)
    {
        for (int i = 0; i < image.Width; i++)
        {
            for (int j = 0; j < image.Height; j++)
            {
                var pixel = image.GetPixel(i, j);
                if (pixel.A != 255)
                    return true;
            }
        }

        //Check 4 corners to check if all of them are with the same color!
        if (!string.IsNullOrEmpty(optionalBgColorGhost))
        {
            if (image.GetPixel(0, 0).ToArgb() == GetColorFromString(optionalBgColorGhost).ToArgb())
            {
                if (image.GetPixel(image.Width - 1, 0).ToArgb() == GetColorFromString(optionalBgColorGhost).ToArgb())
                {
                    if (image.GetPixel(0, image.Height - 1).ToArgb() ==
                        GetColorFromString(optionalBgColorGhost).ToArgb())
                    {
                        if (image.GetPixel(image.Width - 1, image.Height - 1).ToArgb() ==
                            GetColorFromString(optionalBgColorGhost).ToArgb())
                        {
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }

    public static Color GetColorFromString(string colorHex)
    {
        return ColorTranslator.FromHtml(colorHex);
    }

对非透明图像有一个可选的 bg 颜色字符串:

使用示例:

IsImageTransparent(new Bitmap(myImg),"#FFFFFF");

【讨论】:

  • 不确定额外的代码有什么用,但是......为什么不把最后一个 arg 作为 Color 对象而不是 String 呢?更不用说您在代码中解析该字符串 5 次,而不是只解析一次,然后将其保存在 Color 类型变量中。
  • 对于循环遍历所有像素,GetPixel(和SetPixel)不可用。
【解决方案6】:

虽然我知道 OP 与 MagickNet 无关,但它可能会有所帮助。

Magick.Net 为 Imagick 库提供了一个包装器,并包含一个可以轻松访问频道统计信息的功能。

例子

    public bool HasTransparentBackground(MagickImage image)
    {
        if (!image.HasAlpha) return false;

        var statistics = image.Statistics();
        var alphaStats = statistics.GetChannel(PixelChannel.Alpha);

        var alphaMax = Math.Pow(2, alphaStats.Depth);
        return alphaStats.Minimum < alphaMax * .2;
    }

我们首先检查图像是否支持透明度,如果不支持则返回。然后我们得到 alpha 通道的统计信息,并且可以简单地检查 Min 属性。还有一个 Mean 属性,可让您检查图像的“透明程度”。

另见

【讨论】:

    【解决方案7】:

    使用 ImageMagick(命令行)的最简单方法是测试 alpha 通道,如果平均值小于 1(在 0 到 1 的范围内)。 1 完全不透明。所以

    convert image -channel a -separate -format "%[fx:(mean<1)?1:0]" info:
    

    如果返回值为1,则至少有一个像素是透明的;否则(如果为 0),则图像完全不透明。

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 2016-07-02
      • 1970-01-01
      • 2012-06-29
      相关资源
      最近更新 更多