Squeazer
Squeazer

Reputation: 1254

How to bundle images within a .jar file?

Ok i'm having some problems with distributing my .jar file. When i just run the program from NetBeans it works, but if i try to run it from the dist folder it doesn't work (none of the images get loaded).

Here is the hierarchy of my program:

I load images with this function:

public BufferedImage getImg(String path) throws IOException {
    if (this.getClass().getResource(path) != null) {
        return ImageIO.read(this.getClass().getResource(path));
    } else {
        return null;
    }
}

And after that:

BufferedImage image = getImg("../img/static_bg.png");
if (image != null) {
    g.drawImage(image, 309, 884, this);
}

After i build my project the images are in the jar file, but they aren't getting loaded. Any ideas why?

Upvotes: 3

Views: 434

Answers (1)

Stephen Ostermiller
Stephen Ostermiller

Reputation: 25524

To load a file from your war file in a web application, you will need to load it from the "ServletContext". There is a getServletContext() method on every servlet that can be used for this purpose. It can also be obtained from request.getSession().getServletContext()

URL url = servletContext.getResource(name);
if (url == null) return null;
URLConnection resourceConn = url.openConnection();
return ImageIO.read(resourceConn);

Upvotes: 1

Related Questions