Java 识别 Png 图像是否具有 100% 透明的背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23734939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:56:30  来源:igfitidea点击:

Identify whether a Png image has 100 percent transparent Background

javaimageimagemagickpng

提问by Mayank_Thapliyal

I am trying to write a code where I get a png/jpeg image. If it is a png image, I want to check if it's background is 100% transparent. If yes, I want to add white background using image magick.

我正在尝试编写一个代码来获取 png/jpeg 图像。如果它是 png 图像,我想检查它的背景是否 100% 透明。如果是,我想使用图像魔法添加白色背景。

Currently I use image magick's "identify -format %A new.png" which returns true or false based on transparency.

目前我使用图像魔法的“identify -format %A new.png”,它根据透明度返回真或假。

However, is there any way to find out 100 percent background transparency using image magick or java code?

但是,有没有办法使用 image magick 或 java 代码找出 100% 的背景透明度?

采纳答案by Prior99

You could iterate over each pixel in the image and check whether the most significant byte (which is the alpha channel) is zero (as explained here). Do it somehow like this:

你可以在每个像素遍历图像中,检查最显著字节(即alpha通道)是否为零(如解释在这里)。以某种方式这样做:

public static boolean isFullyAlpha(File f) throws IOException {
    BufferedImage img = ImageIO.read(f);
    for(int y = 0; y < img.getHeight(); y++) {
        for(int x = 0; x < img.getWidth(); x++) {
            if(((img.getRGB(x, y) >> 24) & 0xFF) != 0) {
                return false;
            }
        }
    }
    return true;
}