9

I'm trying to load an image into my java application as a BufferedImage, with the intent of having it work in a JAR file. I tried using ImageIO.read(new File("images/grass.png")); which worked in the IDE, but not in the JAR.

I've also tried

(BufferedImage) new ImageIcon(getClass().getResource(
            "/images/grass.png")).getImage();

which won't even work in the IDE because of a NullPointerException. I tried doing it with ../images, /images, and images in the path. None of those work.

Am I missing something here?

fvgs
  • 21,412
  • 9
  • 33
  • 48
  • Where does the image live? If you're using eclipse, does it exist in the resources directory? If you're using NetBeans, does it exist in the arc folder – MadProgrammer Jun 09 '13 at 07:50
  • Using Eclipse, images is its own folder outside of the src folder, but within the project folder. – fvgs Jun 09 '13 at 07:54

1 Answers1

23

new File("images/grass.png") looks for a directory images on the file system, in the current directory, which is the directory from which the application is started. So that's wrong.

ImageIO.read() returns a BufferedImage, and takes a URL or an InputStream as argument. To get an URL of InputStream from the classpath, you use Class.getResource() or Class.getResourceAsStream(). And the path starts with a /, and starts at the root of the classpath.

So, the following code should work if the grass.png file is under the package images in the classpath:

BufferedImage image = ImageIO.read(MyClass.class.getResourceAsStream("/images/grass.png"));

This will work in the IDE is the file is in the runtime classpath. And it will be if the IDE "compiles" it to its target classes directory. To do that, the file must be under a sources directory, along with your Java source files.

Agustin Lopez
  • 1,355
  • 4
  • 18
  • 34
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • My images folder (not package) is outside of the src folder, but within the project folder in Eclipse. So I need to move the images folder into src? – fvgs Jun 09 '13 at 07:52
  • Yes. You must do that. If you don't, eclipse won't copy the images folder to the target directory, and the images thus won't be part of the runtime classpath. – JB Nizet Jun 09 '13 at 07:54
  • Indeed, there we go. It's working properly now. Thanks for the help. – fvgs Jun 09 '13 at 07:55
  • @JBNizet : Perfect answer. – Jad Chahine Apr 16 '16 at 06:28