Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 786
Rapti Avatar asked May 02 '12 18:05

Rapti


3 Answers

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);
    }
}
like image 60
Eng.Fouad Avatar answered Sep 28 '22 03:09

Eng.Fouad


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;
            }
        }
    }
like image 25
Gilbert Le Blanc Avatar answered Sep 28 '22 02:09

Gilbert Le Blanc


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
}
like image 41
Oneiros Avatar answered Sep 28 '22 03:09

Oneiros