Paul Bachmann B4chi
Paul Bachmann B4chi

Reputation: 11

Can´t load image from package

My problem is that I can´t load an image from an subpackage in my java project with maven.

This is my project structure

I tryed some different code snippets but always get a Nullpointer exception.

I tryed:

Image image = new Image("/frontend/pictures/logo.png");
Image image = new Image("frontend/pictures/logo.png");
Image image = new Image("pictures/logo.png");
Image image = new Image(getClass().getResource("frontend/pictures/logo.png").toString());

In an other Project it works fine for me but now I don´t know what I do wrong.

Thanks for your help.

Upvotes: 0

Views: 121

Answers (2)

Paul Bachmann B4chi
Paul Bachmann B4chi

Reputation: 11

It was my bad that I forgot to say that I working with JavaFX. But I fixed my Problem.

I add the picture dir as ressource folder and then:

Image img = new Image(getClass.getRessource("/logo.png").toString);

Thanks for your help.

Upvotes: 0

John Mendoza
John Mendoza

Reputation: 91

Here's a nice image loading method I've created using ImageIcons:

public Image img(String path) {
    ImageIcon icon = new ImageIcon(path);
    return icon.getImage();
}

Then when you wish to load an image, just use:

Image image = img("frontend/pictures/logo.png") 

and this should work. Note that if you want to use a runnable JAR, you'll have to use this implementation:

static Image setImage(String path) {
    Image tmp = null;
    try {
        tmp = ImageIO.read(/*Class name*/.class.getResourceAsStream(path));
    } catch (IOException e){
        e.printStackTrace();
    }
    return tmp;
}

and feed in:

Image image = setImage("/org/.../logo.png");

with your image placed in some subfolder inside the org folder of the JAR.

Upvotes: 2

Related Questions