简体   繁体   中英

Loading an image in a JAR

At the moment I am trying to load images in a way that will be "JAR friendly" so-to-speak, but I am having trouble getting it the images to load.

Currently the folders are laid out as such:

>src
  >package.name.etc
    ImageLoader.java
>assets
  >images
    >menu
      background.png

At the moment I am trying to implement the following code:

    public Image loadImage(String filename) {
        Toolkit tk = Toolkit.getDefaultToolkit();
        URL url = null;
        try {
            url = this.getClass().getResource("assets/images/menu/" + filename);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Image i = tk.getImage(url);
        return i;
    }

and in another method where I am trying to load the image:

Image background = loadImage("background.png");

This simply returns a null pointer exception stating there is no image there, and I am really not sure how to the correct directory for the image to work. Any help is appreciated, thanks.

EDIT: This is the error I get, and I am not sure where I should be catching it from.

Uncaught error fetching image:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(Unknown Source)
    at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
    at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
    at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
    at sun.awt.image.ImageFetcher.run(Unknown Source)

In order to include in the jar an image, I have done the following steps :

  1. Use the following hierarchy:

    src>

    packageName <--- code is here

    packageName.resources <--- image structure here

  2. Configure the build path to include packageName.resources
  3. Get the Image with the following code :

try {
    BufferedImage img = 
        ImageIO.read(this.getClass().getResourceAsStream("resources/"+filename));
} catch (IOException e) {
    e.printStackTrace();
}   

请查看此内容并检查是否需要assets/images/menu/零件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM