简体   繁体   中英

Filling a BufferedImage with transparent pixels

This has been asked here and here - but all the answers in both do not work (I've spent over an hour trying them all).

Part of the problem I think is the background needs to be set to white with an alpha of 0. That way, for programs or formats that don't support alpha, the color is white instead of black.

So my question is, how do I set a created BufferedImage to a background of all transparent white?

My code (sets it to non-transparent white):

image = new BufferedImage((sectPage.getPaperWidth().getValue() * dpi) / 1440,
        (sectPage.getPaperHeight().getValue() * dpi) / 1440,
        BufferedImage.TYPE_INT_ARGB);
// bugbug - https://stackoverflow.com/questions/321736/how-to-set-dpi-information-in-an-image
graphics = image.createGraphics();

graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

// bugbug - want all clear
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0,0,(sectPage.getPaperWidth().getValue() * dpi) / 1440, (sectPage.getPaperHeight().getValue() * dpi) / 1440);

Also tried passing in a color with alpha set to 0 and setBackground(). Got a back background in both of those cases.

This was a dumb mistake on my part. I'm leaving this in for others that hit the same problem.

graphics.setBackground(new Color(0x00FFFFFF, true));
graphics.clearRect(0, 0, sectPage.getPaperWidth().getValue(), sectPage.getPaperHeight().getValue());

works. My problem was the program I was viewing it with used black for the clear background. It used to use the standard white/grey checkerboard. So for anyone who thinks this does not work...

View your bitmap with multiple programs!

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