7

I am trying to load a binary image file to do some processing inside my server-side Java code. I am currently placing my image in the package where my executing class exists and calling:

Image img = Image.getInstance(this.getClass().getResource("logo.png"));

This works fine when I'm running Tomcat on my development box in an exploded war setup, but when I deploy to a server running Tomcat where it doesn't explode war files, the call to getResource returns null.

I've also tried moving the image to my context root and accessing it like this:

Image img = Image.getInstance(this.getClass().getResource("/../../logo.png"));

Again, this works on my development box, but not when I deploy it elsewhere.

Is there a better way to access this file? What am I doing wrong?

Thanks!!

11101101b
  • 7,679
  • 2
  • 42
  • 52
  • I probably should have also mentioned that I am using Maven to build my web-app. I have a complete answer that fixes my problem, but I can't post it for 8 hours on my own question. – 11101101b Jan 06 '12 at 21:29
  • Put resources in your "src/main/resources" directory. Then access them with: this.getClass().getResource("/logo.png"); or: Thread.currentThread().getContextClassLoader().getResource("logo.png"); – 11101101b Jan 06 '12 at 21:31

2 Answers2

8

If you are building using Maven, you'll want to make sure the image actually gets placed into the archive.

Put resources in your src/main/resources directory. Then access them with:

this.getClass().getResource("/logo.png"); 

or:

Thread.currentThread().getContextClassLoader().getResource("logo.png"); 

(Code samples from comment above, but put in the answer to be more visible)

checketts
  • 14,167
  • 10
  • 53
  • 82
1

You could put your images at the root of your classpath and try this:

Thread.currentThread().getContextClassLoader()
               .getResource("logo.png");
Perception
  • 79,279
  • 19
  • 185
  • 195
  • 2
    +1 - By root of your classpath, "WEB-INF/classes" inside the WAR file is where many will put said resource(s). Though they may organize by using folders like "images/logo.png" within there. – rfeak Jan 06 '12 at 20:51