在java中以编程方式删除图像文件后,ImageIcon将显示路径中已删除的文件

问题描述 投票:0回答:1

我的项目正在加载一个ImageIcon,它是从路径中删除的图像。

最初,我已经将图像从文件路径加载到ImageIcon,之后我从路径中删除了图像文件。再一次,我试图将已删除路径中的图像加载到Same ImageIcon对象,它显示已删除的图像。

    File file = new File(Utility.generate_file_path("Ec_resized_image\\ansi.png"));
    System.out.println(Utility.generate_file_path("Ec_resized_image\\ansi.png")
        + " : " + file.exists());

    ImageIcon icon = new ImageIcon(Utility.generate_file_path("Ec_resized_image\\ansi.png"));           
    System.out.println("Width: " + icon.getIconWidth());//Here it the image width is showing 1920 
    file.delete();       //here I am deleting the file 

    System.out.println(Utility.generate_file_path("Ec_resized_image\\ansi.png") + " : " + file.exists()); // here file.exists() says false. 

    icon = new ImageIcon(Utility.generate_file_path("Ec_resized_image\\ansi.png")); // Again loading the deleted path
    System.out.println("Width: " + icon.getIconWidth());////Here it the image width is showing again 1920
java imageicon
1个回答
2
投票

ImageIcon(filename)将图像的实际加载委托给Toolkit.getDefaultToolkit().getImage(filename)(API可能没有这样定义,但我在源代码中看到了这一点。)

来自Toolkit.getImage()的Javadoc:

底层工具包尝试将具有相同文件名的多个请求解析为同一返回的Image。 ... 如果指定文件中包含的图像数据发生更改,则从此方法返回的Image对象可能仍包含在先前调用之后从文件加载的陈旧信息。

然后这个javadoc继续:

可以通过在返回的flush()上调用Image方法手动丢弃以前加载的图像数据。

因此,正如梅纳所说,icon.getImage().flush()应该做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.