Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing transparency in PNG BufferedImage

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.

like image 631
user4020527 Avatar asked Nov 13 '14 21:11

user4020527


1 Answers

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

like image 159
MadProgrammer Avatar answered Oct 21 '22 04:10

MadProgrammer