7

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!

Rapti
  • 2,520
  • 3
  • 20
  • 23

3 Answers3

7
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);
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • This is clean and efficient but the logic of this function is backwards. According to the javadoc on [Color](http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html), "an alpha value of 1.0 or 255 means that the color is completely opaque and an alpha value of 0 or 0.0 means that the color is completely transparent." This function returns true if the alpha bits are 255 meaning the pixel is opaque. – Fr33dan Dec 04 '13 at 14:41
  • looks like typo: getRBG need to replace to getRGB according to https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#getRGB(int,%20int) – Enginer Oct 13 '19 at 12:49
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;
            }
        }
    }
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
1
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
}
Oneiros
  • 4,328
  • 6
  • 40
  • 69