Getting images from a .jar file

青春壹個敷衍的年華 提交于 2019-11-26 17:20:53

问题


I need to get res folder to compile when I export a executable jar file in eclipse also when I use the getClass().getResource() method it doesn't work.

Current reading image code

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

Code that doesn't work

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

回答1:


I have now fixed the problem - this is the code that works

 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;

}

The value of fileName is just an image name eg BufferedImage img = loadImage("background.png");

Thank you all for your help.




回答2:


Either:

  • your path is wrong, you should get an error message if so, check it to see what path it actually tries, might not be what you think. Or debug and see what path it tries or even just print the path it tries.

or

  • it's not in the jar. Check the jar file with a zip-program and/or rename it to have zip in the and open it to check that the file is really there.


来源:https://stackoverflow.com/questions/10489773/getting-images-from-a-jar-file

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