我一直在跟踪一些使用Graphics2D来更改BufferedImage背景颜色的StackOverflow链接。
我正在从事的项目要求我从给定的URL中读取png图像;检索到的png图像具有透明背景,我想将其设置为白色。
这就是我所拥有的:
String u = this.format() ;
BufferedImage image = null ;
try{
URL url = new URL(u) ;
image = ImageIO.read(url) ;
Graphics2D graphics = image.createGraphics() ;
graphics.setBackground(Color.WHITE) ;
graphics.clearRect(0,image.getWidth(),image.getHeight()) ;
ImageIO.write(image,"png",new File(outPath + fileName)) ;
graphics.dispose() ;
}
catch(IOException e){
e.printStackTrace() ;
}
我遇到的问题是,当我查看图像时,图像显示为纯白色框。显然,我在检索到的现有图像上覆盖了白色背景。
如何保留原始图像并仅更改背景?还是先设置背景,然后覆盖检索到的图像?