1

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.

Community
  • 1
  • 1
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • Create a `Color` with alpha channel, with the help of constructor `Color(int r, int g, int b, int a)` for example. – Jean-Baptiste Yunès May 10 '17 at 17:09
  • @Jean-BaptisteYunès I should have said I tried that - got black. – David Thielen May 10 '17 at 19:38
  • What do you expect? What do you do with the image after? – Jean-Baptiste Yunès May 10 '17 at 20:09
  • See my answer [here](http://stackoverflow.com/a/43891658/1428606) for how to fill a rectangle with a transparent color (use option 2, with `new Color(0x00FFFFFF, true)` or `new Color(255, 255, 255, 0)`). This will do what you ask for. But I'm not sure if the effect will be what you wanted, as image encoders could normalize all transparent colors (to transparent black), or software that don't support alpha might just replace it with a different color. – Harald K May 11 '17 at 07:31

1 Answers1

0

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!

David Thielen
  • 28,723
  • 34
  • 119
  • 193