Java Image Loading from .jar File

醉酒当歌 提交于 2021-01-27 17:12:22

问题


I'm trying to load an image from a folder named Custom that the user places images into. Here is the method I used to load images:

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\\Custom\\" + path + ".png";

    try{
        img = ImageIO.read(this.getClass().getResource(s2));//gets image from file path
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}

Here is the program path method

public String getProgramPath(){
    File f = new File("./Resources/Sprtes/blank.png");
    String s = f.getAbsolutePath();
    String[] stringArr = s.split("Resources");
    String s2 = stringArr[0];
    s2 = s2.substring(0, s2.length() - 3);
    return s2;
}

When I run the code everything works fine but the issue appears when I try to run the program as a .jar file. When I run it using a .jar file, the image doesn't load. This is where the custom folder is in relation to the .jar file:

File Structure

How should I change the method to make sure that this works?


回答1:


So I figured out the problem thanks to Luke Lee and Olithegoalie,

img = ImageIO.read(this.getClass().getResource(s2)); Doesn't work if the path goes outside the jar so I had to change it to

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\\Custom\\" + path + ".png";
    try{
        img = ImageIO.read(new File(s2));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}


来源:https://stackoverflow.com/questions/38175263/java-image-loading-from-jar-file

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