7

I'm reading a PNG image with the following code:

BufferedImage img = ImageIO.read(new URL(url));

Upon displaying it, there is a black background, which I know is caused from PNG transparency.

I found solutions to this problem suggesting the use of BufferedImage.TYPE_INT_RGB, however I am unsure how to apply this to my code above.

user4020527
  • 1
  • 8
  • 20

1 Answers1

30

Create a second BufferedImage of type TYPE_INT_RGB...

BufferedImage copy = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);

Paint the original to the copy...

Graphics2D g2d = copy.createGraphics();
g2d.setColor(Color.WHITE); // Or what ever fill color you want...
g2d.fillRect(0, 0, copy.getWidth(), copy.getHeight());
g2d.drawImage(img, 0, 0, null);
g2d.dispose();

You now have a non transparent version of the image...

To save the image, take a look at Writing/Saving an Image

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I needed to draw the image to the entire rectangle, so basically filling it completely. Syntax slightly varies: `g2d.drawImage(img, 0, 0, copy.getWidth(), copy.getHeight(), null);` – Jan Petzold Dec 20 '17 at 21:04
  • @JanPetzold The solution would depend on the requirements, personally, I use a "scale to fill" approach which maintains the aspect ratio of the original image, [for example](https://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928). In most cases, the inbuilt scaling algorithms focus on speed over quality, so you should just be wary of that – MadProgrammer Dec 20 '17 at 21:09
  • This still blends the original source image onto the `copy `, so whatever background color you choose for `fillRect` will be partially visible on any pixel that wasn't completely opaque. Is there a standard way to ignore the alpha blending entirely and just assume all source pixels were completely opaque? – MasterHD Mar 22 '19 at 11:29
  • Short answer is no. The long answer is, you try different alpha blends – MadProgrammer Mar 22 '19 at 20:57