How do I go about adding an image into a java project with eclipse?
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
).
Related videos on Youtube
ct_
Updated on August 31, 2020Comments
-
ct_ over 3 years
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!
-
MeBigFatGuy about 13 yearsagreed, OP the reason is, that eclipse automatically copies files from the src directories to the classes directory. It does not do this for ordinary directories, and why you get that error.
-
durron597 over 11 yearsThis is not as good of an answer as the previous 2 answers. Please read the other answers before answering.
-
CodeMed almost 11 yearsI see this posting is 2 years old, but for the people who reach through the search engines, I am adding that, if you run this code from within a static method, it will throw an error unless you change the definition of the input variable to: InputStream input = LoadImg.class.getClassLoader().getResourceAsStream("hockeypuck.jpg");
-
TomeeNS almost 8 yearsBut, how you add the image to the folder in Eclipse?
-
Lawrence over 7 years@CodeMed This answer provides another way to hook in:
getClass().getResourceAsStream("image.jpg")
. -
Ivan about 5 years"Place the image in a source folder", that solved the problem, thank you so much!