0

I tried it like this:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}

That did not seem to work for me. My image is in a (eclipse) res-folder.

When I look up the whole path (C:/...) it seems to work. How can I make it load without the whole thing when it is in the same project?

  • When included within the context of the application (ie in the resource or source locations), you can't treat them as files, instead, you need to use `Class#getResource` to obtain a reference to them – MadProgrammer Apr 03 '23 at 22:56
  • Why? I don't understand... – Jens Meier Apr 03 '23 at 23:12
  • 1
    The problem is in how the image gets stored. If you include the image in the "resources" directory of your project, the image will be included in the resulting Jar file, when the project is built and exported. This places the image inside the jar (or zip file) rendering it no longer accessible as a "file on the file system". This solves an otherwise annoying issue of having to "find" the image some where on the file system when you don't actually have any clue where it might actually be - as you working location could be any where, so relative and absolute paths become useless – MadProgrammer Apr 03 '23 at 23:26
  • Ah ok, thank you. The problem I see now is that my ImageUtil class needs a static method to load the image. How could I then load the image when getClass() can not be used?! – Jens Meier Apr 04 '23 at 08:59
  • `YourClass.class.getResource` – MadProgrammer Apr 04 '23 at 21:33

0 Answers0