0

I want to add a picture to my GUI program created using Eclipse and MyEclipse (for GUI visual design) from the resource pictures I pasted earlier in the project.

I managed to load pictures that lies just beside the .JAR file using

image = ImageIO.read(new File("imageFile.jpg"));

But I want to use the image from my resources "src" folder directly , so that the .JAR file is a standalone file yet loads pictures nicely.

I tried to make it

image = ImageIO.read(new File("src/ldtlogo3.jpg"));

I use this method when exporting the .JAR file Java: export to an .jar file in eclipse

Community
  • 1
  • 1
sherif
  • 33
  • 1
  • 7

1 Answers1

2

Use the overloaded ImageIO.read method taking an InputStream as a parameter, and use MyClass.class.getResourceAsStream() to get this input stream. getResourceAsStream loads a resource from the classpath (and thus from the JAR of your application). Its api doc will tell you which path it expects.

Note that the src directory is used to hold your Java source files. The jar doesn't contain it. It contains the .class files, in a hierarchy which directly maps the package hierarchy. Eclipse will automatically "compile" the image file by copying to the output directory, along with the .class files.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I did this and it shows a null exception: InputStream a=LoadImage.class.getResourceAsStream("src/imageFile.jpg"); image = ImageIO.read(a); – sherif Jul 04 '11 at 21:04
  • @sherif get rid of the `src/`. – Lynch Jul 04 '11 at 21:08
  • @sherif: open your jar file with a zip tool (winzip or anything else), and use the path of the image file. For example: /com/yourcompany/yourproject/imageFile.jpg. If the image is at the root of the tree, use /imageFile.jpg. The src attribute exists only in your development tree. At runtime, the jar is used, which does not contain the src directory. – JB Nizet Jul 04 '11 at 21:13
  • @JB Nizet Thank you man, it worked :) but I did something else, I moved the pictures inside the package that has the main function, then referred to the resource with just it's name, I assume your method will work too , thank you – sherif Jul 04 '11 at 21:37