Java图片绘制叠加问题:循环生成图片时旧图残留
问题原因
你遇到的图片叠加问题,核心是重复使用了同一个imageVoid对象。代码里newBack = imageVoid;只是把原空白底图的引用赋值给新变量,并没有创建全新的底图实例。每次循环调用drawImage时,都是在同一个底图上绘制,之前的内容不会被清空,导致后续图片叠加旧内容。
解决方法
每次循环时,创建imageVoid的全新副本,基于这个副本绘制缩放后的图片,确保每次都是干净的空白底图。
关键修改代码
替换原来的newBack = imageVoid;,改为创建底图副本:
// 创建和原底图尺寸、类型一致的新BufferedImage newBack = new BufferedImage(imageVoid.getWidth(), imageVoid.getHeight(), imageVoid.getType()); // 将原空白底图内容绘制到新对象中 Graphics2D bg = newBack.createGraphics(); bg.drawImage(imageVoid, 0, 0, null); bg.dispose(); // 再绘制缩放后的图片 newBack.createGraphics().drawImage(dimg,25,0,null);
修改后的完整代码
public static void downloadPictures(ArrayList<Channel> channels){ String url; File output; BufferedImage imageVoid = null; BufferedImage imageNotFound = null; BufferedImage newBack; BufferedImage srcImage; try { imageNotFound = ImageIO.read(new File(notImagePass)); imageVoid = ImageIO.read(new File(voidPass)); } catch (IOException e) { System.out.println("There is no picture for not founded file OR no void picture"); } //============================== //==============================Making pictures and checking if link exists //============================== for (Channel channel : channels) { url = channel.getLink(); if (!channel.ifLinkExists()) { //=====link exists try (InputStream in = URI.create(url).toURL().openStream()) { srcImage = ImageIO.read(in); Image tmp = srcImage.getScaledInstance(75,75,Image.SCALE_DEFAULT); BufferedImage dimg = new BufferedImage(75,75,BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); // 关键修改:创建空白底图的全新副本 newBack = new BufferedImage(imageVoid.getWidth(), imageVoid.getHeight(), imageVoid.getType()); Graphics2D bg = newBack.createGraphics(); bg.drawImage(imageVoid, 0, 0, null); bg.dispose(); newBack.createGraphics().drawImage(dimg,25,0,null); ImageIO.write(newBack, "png", new File(picturesPass + channel.getName() + ".png")); } catch (IOException e) { //=====link exists but source not founded output = new File(picturesPass + channel.getName() + ".png"); try { ImageIO.write(imageNotFound, "png",output); } catch (IOException ex) { throw new RuntimeException(ex); } } } else { //=====link doesnt exists output = new File(picturesPass + channel.getName() + ".png"); try { ImageIO.write(imageNotFound, "png",output); } catch (IOException e) { throw new RuntimeException(e); } } } }
内容的提问来源于stack exchange,提问作者Bawich
相关产品推荐
相关产品推荐

