Removing transparency in PNG BufferedImage

大憨熊 提交于 2019-11-27 07:58:27

问题


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:


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



来源:https://stackoverflow.com/questions/26918675/removing-transparency-in-png-bufferedimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!