Removing transparency in PNG BufferedImage

8.7k Views Asked by At

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.

1

There are 1 best solutions below

4
On BEST ANSWER

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