简体   繁体   English

无法从单个BufferedImage像素获取正确的Alpha值

[英]Can't get correct alpha values from individual BufferedImage pixels

I need to get RGBA values, modify RGB, then set RGB (and A) values again. 我需要获取RGBA值,修改RGB,然后再次设置RGB(和A)值。

However, it seems to return 255 for all the pixels, even though I know the image I'm loading has transparent pixels in it. 但是,即使我知道所加载的图像中包含透明像素,它似乎也为所有像素返回255

Here's an SSCCE 这是一个SSCCE

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class TestImage {

    public static void main(String args[]) {
        try {
            BufferedImage image = ImageIO.read(new File("/home/affy/Pictures/salamenceavatar.png"));

            BufferedImage buff = new BufferedImage(
                    image.getWidth(),
                    image.getHeight(),
                    BufferedImage.TYPE_INT_ARGB
            );

            Graphics2D g = buff.createGraphics();
            g.drawImage(image, 0, 0, null);

            for(int x = 0; x < image.getWidth(); x++) {
                for(int y = 0; y < image.getHeight(); y++) {
                    Color c = new Color(buff.getRGB(x, y));
                    int alpha = c.getAlpha();
                    System.out.println(alpha);
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Use Color(int, boolean) instead, passing it true to tell it you want to extract the alpha value from the supplied packed int 改用Color(int, boolean) ,将其传递为true表示您要从提供的打包int提取alpha值

Color c = new Color(buff.getRGB(x, y), true);

From the JavaDocs... 从JavaDocs ...

Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7. 使用指定的组合RGBA值创建sRGB颜色,该值由位24-31中的alpha分量,位16-23中的红色分量,位8-15中的绿色分量和位0-7中的蓝色分量组成。 If the hasalpha argument is false, alpha is defaulted to 255. 如果hasalpha参数为false,则alpha默认为255。

Parameters: 参数:

rgba - the combined RGBA components rgba-组合的RGBA组件
hasalpha - true if the alpha bits are valid; hasalpha-如果alpha位有效,则为true;否则为false。 false otherwise 否则为假

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM