How can i find out where a BufferedImage has Alpha in Java?

蓝咒 提交于 2019-12-10 13:36:09

问题


I've got a BuferredImage and a boolean[][] array. I want to set the array to true where the image is completely transparant.

Something like:

for(int x = 0; x < width; x++) {
    for(int y = 0; y < height; y++) {
        alphaArray[x][y] = bufferedImage.getAlpha(x, y) == 0;
    }
}

But the getAlpha(x, y) method does not exist, and I did not find anything else I can use. There is a getRGB(x, y) method, but I'm not sure if it contains the alpha value or how to extract it.

Can anyone help me? Thank you!


回答1:


public static boolean isAlpha(BufferedImage image, int x, int y)
{
    return image.getRBG(x, y) & 0xFF000000 == 0xFF000000;
}
for(int x = 0; x < width; x++)
{
    for(int y = 0; y < height; y++)
    {
        alphaArray[x][y] = isAlpha(bufferedImage, x, y);
    }
}



回答2:


Try this:

    Raster raster = bufferedImage.getAlphaRaster();
    if (raster != null) {
        int[] alphaPixel = new int[raster.getNumBands()];
        for (int x = 0; x < raster.getWidth(); x++) {
            for (int y = 0; y < raster.getHeight(); y++) {
                raster.getPixel(x, y, alphaPixel);
                alphaArray[x][y] = alphaPixel[0] == 0x00;
            }
        }
    }



回答3:


public boolean isAlpha(BufferedImage image, int x, int y) {
    Color pixel = new Color(image.getRGB(x, y), true);
    return pixel.getAlpha() > 0; //or "== 255" if you prefer
}


来源:https://stackoverflow.com/questions/10419838/how-can-i-find-out-where-a-bufferedimage-has-alpha-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!