Loading images in Java

In the Java project I am working on I needed to load an image from a file (representing a unknown user profile) for display to the user. This is easy to do. However, in production the application runs from a jar file, so I want my app to find the image inside the jar file. There are a number of example web pages on how to load images from jar files.

But I wanted something that also worked when I was developing in Eclipse, and none of the examples I found worked unless the application was running from a jar file. Here’s my simple solution:


// Try to grab unknown profile icon from JAR file
URL picturePath = this.getClass().getResource("/images/unknown-profile.jpg");
// However, if we are running from Eclipse then no JAR file
if (picturePath == null) {
  try {
    picturePath = new URL("file://" + System.getProperty("user.dir")
        + "/images/unknown-profile.jpg");
  }
  catch (MalformedURLException e) {
    System.out.println(bogusErrMessage);
  }
}
if (picturePath != null) {
  this.picture = new ImageIcon(picturePath);
  this.profile.setPhotoUrl(picturePath.toString());
}

Of course you need to have an “images” directory at the top level of your project directory, and you need to write appropriate ant tasks to copy over your images directory to your build directory when you create the jar file.

Advertisements

3 thoughts on “Loading images in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s