Search code examples
javapngtransparencybufferedimage

Transparent PNG - BufferedImage contains not existing pixels - java


I have got BufferedImage and method getRGB(...) shows me pixel in position 456, 1959, but I cannot see any color in this position in any image editor. I have got two images with transparency. ImageOne was created in my java application. ImageTwo is ImageOne (ImageOne was open in Affinity Photo and saved as ImageTwo without any change).

If I open ImageOne or ImageTwo in any image editor I can see two same images. Images to download: ImageOne + ImageTwo or HERE or HERE

But in java application it seems, that images are different. This code print RGB color for pixel 456, 1959

    private static void testImage() {
    try {
        File fOne = new File("d:\\test\\ImageOne.png");
        File fTwo = new File("d:\\test\\ImageTwo.png");
        
        BufferedImage imageOne = ImageIO.read(fOne);
        BufferedImage imageTwo = ImageIO.read(fTwo);
        
        Color cOne = new Color(imageOne.getRGB(456, 1959));
        System.out.println("imageOne = " + cOne.getRGB() + " RGBA = " + cOne.getRed() + "," + cOne.getGreen() + "," + cOne.getBlue() + "," + cOne.getAlpha());
        
        Color cTwo = new Color(imageTwo.getRGB(456, 1959));
        System.out.println("imageTwo = " + cTwo.getRGB() + " RGBA = " + cTwo.getRed() + "," + cTwo.getGreen() + "," + cTwo.getBlue() + "," + cTwo.getAlpha());
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The result is:

imageOne = -8355712 RGBA = 128,128,128,255
imageTwo = -16777216 RGBA = 0,0,0,255

Is it possible to clear BufferedImage from these "invisible" pixels? Have you any idea why is pixel in ImageOne and why I can see it only in java? Why is the pixel "invisible" for image editors? Thank you.


Solution

  • I thought this is totally legit. The alpha channel is 255, which means the ink is fully transparent.

    This assumption is wrong as per https://www.w3.org/TR/PNG-DataRep.html#DR.Alpha-channel: An alpha value of zero represents full transparency, and a value of (2^bitdepth)-1 represents a fully opaque pixel.

    Which means I do not have an explanation why in graphics programs the picture should be looking the same - which is the symptom originally described.