Josh
Josh

Reputation: 277

Java Image Loading from .jar File

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?

Upvotes: 2

Views: 1048

Answers (1)

Josh
Josh

Reputation: 277

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;
}

Upvotes: 1

Related Questions