Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including Images with an executable jar

I have been browsing Stackoverflow all day looking for how to do this and I have not been successful yet

I am packaging a quick game I made into a executable jar but I didnt reference the images correctly I just referenced the files

background = ImageIO.read(new File("wood.jpeg"));

I have my classes in src default package Im not sure where I should add the images or if I have to add it to the build path or correct way of adding the images to the build path in the newest version of eclipse

like image 270
Mintybacon Avatar asked Sep 19 '12 04:09

Mintybacon


People also ask

How do I add an image to a JAR file?

First step: Put your image in a defined location in your JAR-file. If you put it into the src-folder, maybe your IDE or your build-tool will package it to the JAR automatically. Otherwise check the documentation of your IDE/build-tool, in which location you have to put it.

Can JAR files contain images?

In simple words, a JAR file is a file that contains a compressed version of . class files, audio files, image files, or directories.

How do I bundle images in a JAR file?

Add the images directory as a source root for you project. This will change the content of the panel on the right side of the dialog. Press the 'Add Folder...' button that appears next to the 'Source Package Folders' table. A FileChooser will appear. Use this chooser to select the images folder and press the OK button.

How do I add a resource file to a JAR file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!


1 Answers

Files in a Jar are not files in the sense of a file on disk. They are simply a (possibly) compressed stream of bytes.

Java makes it easy to extract these "resources" from Jar files through the use of the ClassLoader

background = ImageIO.read(getClass().getResource("/wood.jpeg"));

Should work...

This will return a URL which ImageIO can use to load the resource.

You could also have a read of

  • Classpath resource within jar
  • Jar get image as resource
  • Load a resource in Jar

And I could list some more. So, yeah, it gets asked a lot ;)

like image 69
MadProgrammer Avatar answered Oct 03 '22 01:10

MadProgrammer