javaimagecompositing

Transparent regions of a BufferedImage are writing out black


I know this is something to do with compositing but I can't work out what. In an earlier section of code, a particular list of pixels in a BufferedImage are set to be transparent black:

        for(Pixel p : closed){
            Color c = new Color(image.getRGB(p.x, p.y));
            Color newC = new Color(0,0,0, 0);
            image.setRGB(p.x, p.y, newC.getRGB() & 0x00000000);
        }

        if(andCrop){
            image = image.getSubimage(left, top, right-left, bottom-top);
        }


        return image;

Then I attempt to write the image out:

try {

            BufferedImage out = new BufferedImage(image.getWidth(), image.getHeight(), java.awt.Transparency.TRANSLUCENT);
            Graphics2D g2d = out.createGraphics();
            g2d.setComposite(AlphaComposite.Clear);
            g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
            g2d.setComposite(AlphaComposite.Src);
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            g2d.dispose();

            File outputfile = new File(file);
            ImageIO.write(out, "png", outputfile);
        } catch (IOException e) {

        }

Now, I know that 'out' is clear before I attempt to draw the image onto it. What I'm not getting is what's wrong with my compositing. Instead of coming out as transparent, I'm getting full-black.

All bufferedimages used are INT_ARGB.

EDIT - This has been solved. The image source was from ImageIO.read and the BufferedImage returned did not support alpha. A quick post-read conversion let the rest of the code run smoothly.


Solution

  • Whelp, this has been downvoted now so I'm not sure this will be relevant, but the issue was that the original BufferedImage was being read in by ImageIO, and this image was not supporting ARGB. A quick post-read conversion allowed the rest of the code to work.