0

I know questions like this have been asked before, but I have looked and tried a lot of the answers and none of them work. I am trying to use an image inside a .jar file. The image is stored in the directory /world/maps/map1.jpg.

            BufferedImage bigImg;
            try
            {
                bigImg = ImageIO.read(getClass().getResourceAsStream("/world/maps/" + name + ".jpg"));
            }
            catch(Exception e)
            {
                System.out.println(e + ": is the error");
                bigImg = null;
            }

Thanks for the help.

forgot to make it clear but class file is in the same directory as image

2 Answers2

1

If you directory tree is something like:

SomeClass.class
world
|--maps
   |--image.jpg

You can use some reference like:

SomeClass.class.getResource("./world/maps/image.jpg")

If the class is inside some another directory, just add ../ to the path.

elias
  • 15,010
  • 4
  • 40
  • 65
  • I tried that and it doesn't work, On compile is says incompatible types (requires bufferedimage got url), also they are in same directory, i made it /world/maps because that was an answer on a similar thread. It didn't work when it was a .jar file – Kieran Jones Apr 05 '13 at 17:26
  • I don't understand. `BufferedImage bigImg = ImageIO.read(SomeClass.class.getResource("./world/maps/image.jpg"))` works correctly. – elias Apr 05 '13 at 18:44
  • Are you using Jdk 5 or higher to compile? Some tools like Maven can use an older version of the Jdk by default. – elias Apr 08 '13 at 17:42
0

The class on which getClass() is called must reside in the same jar. And the path must be case sensitive. Are you sure that name is "image"?

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138