简体   繁体   中英

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.

Things that comes to my mind... (thanks to Andrew):

java.awt.Transparency.TRANSLUCENT = 3
TYPE_INT_ARGB = 2
TYPE_INT_ARGB_PRE = 3

public BufferedImage(int width,
                 int height,
                 int imageType)

Constructs a BufferedImage of one of the predefined image types. (TYPE_...)

http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/image/BufferedImage.html

so it seems as basically it's a mixup.

Besides, what is the effect you want to achieve? you clear an empty image, then draw fully transparent pixels to it... I just don't get it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM