从.jar文件中获取图像

当我在eclipse中导出可执行jar文件时,我还需要获取res文件夹,当我使用getClass().getResource()方法时它不起作用。

当前读取图像代码

 public Image loadImage(String fileName) { return new ImageIcon(fileName).getImage(); } 

代码不起作用

 public Image loadImage(String fileName) { return new ImageIcon(getClass().getResource(fileName).getImage(); } 

或者:

  • 你的路径是错误的,你应该收到一条错误信息,如果是这样的话,检查它看看它实际尝试的路径,可能不是你的想法。 或者调试并查看它尝试的路径,甚至只打印它尝试的路径。

要么

  • 它不在jar子里。 用zip程序检查jar文件和/或将其重命名为zip并打开它以检查文件是否真的存在。

我现在已经修复了问题 – 这是可行的代码

  public BufferedImage loadImage(String fileName){ BufferedImage buff = null; try { buff = ImageIO.read(getClass().getResourceAsStream(fileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return buff; } 

fileName的值只是一个图像名称,例如BufferedImage img = loadImage(“background.png”);

感谢大家的帮助。