微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Magick++ 找出图像是否具有透明度

如何解决Magick++ 找出图像是否具有透明度

我试图找出图像(Magick++ 类)是否不透明/是否具有透明像素。我当前的测试代码如下所示:

    Image orig;
    orig.read(inputPath.c_str());

    bool hasAlpha = orig.alpha();
    printf("Alpha: %s %s\n",inputPath.c_str(),hasAlpha ? "yes" : "no");

这正确地为 jpg 输出“否”,为具有透明度的 png 输出“是”,但不幸的是,对于没有透明像素的 PNG 也会报告“是”。

使用命令 identify -format '%[opaque]' image.png,imagemagick 能够为所有文件正确检测到这一点,因此它能够找到这一点,但我想避免出于各种原因调用外部程序,我可以'在文档中或通过谷歌找不到合适的方法。如何通过 Magick++ 在代码中找到这一点?

谢谢!

解决方法

使用ImageMagick-7,我相信你需要的方法是Magick::Image::isOpaque();它调用相同的 MagickCore 方法来计算 '%[opaque]'


bool hasAlpha = !orig.isOpaque();
printf("Alpha: %s %s\n",inputPath.c_str(),hasAlpha ? "yes" : "no");
,

似乎唯一的方法是手动检查所有像素。我的代码如下,以防其他人将来遇到此问题。使用前需要注意的两个重要事项:

  • 检查 alpha 通道的方法似乎已在 ImageMagick7 中重命名为 alpha,之前为 matte()。如果无法编译,请检查您的版本。
  • 我只检查 Alpha 通道中是否缺少 Alpha 通道或透明度。还有其他我没有检查的透明方法(即​​将特定颜色设置为透明)。
// assumed preamble:
//#include <Magick++.h>
//using namespace Magick;

/**
 * Finds out whether an image is opaque (has no transparent pixels). Tested for jpeg and png inputs.
 * @param baseImage The image to check.
 * @return True if opaque,false otherwise.
 */
bool IsImageOpaque(const Image& baseImage) {
    // if the image has no alpha channel,we're done now
    if (!baseImage.alpha())
        return true;

    // if it does not work that simple,we need to check the alpha channel for non-opaque values
    // it seems to be best practice to clone the image beforehand
    Image img(baseImage);

    // find image width and height for iteration
    int imgWidth = img.columns();
    int imgHeight = img.rows();

    // iterate the whole image
    for ( int row = 0; row <= imgHeight; row++ )
    {
        for ( int column = 0; column <= imgWidth; column++ )
        {
            // get each pixel
            Color px = img.pixelColor( column,row );
            // opaque means that the alpha channel has the max value,so if we find a pixel where this condition is not
            // met,the image is not opaque
            if (px.quantumAlpha() != QuantumRange)
                return false;
        }
    }

    // if we did not exit early,we did not find a transparent pixel and,therefore,the image is opaque
    // note that we did *not* check for other transparency methods,such as a color which is marked as transparent (gif
    // uses this AFAIK),so be vary for inputs other than png or jpg.
    return true;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。