ct_ ct_ - 3 months ago 10
Java Question

How do I go about adding an image into a java project with eclipse?

I've done a lot of reading around SO and Google links.

I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.

Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)

Here is my method.

I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"

Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".

Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.

I then use the following code:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);


And at this point, I run the test program and get this error:

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at Test.main(Test.java:17)


Thanks for any help in advance!

Answer

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).