0

I know this issue has been discussed a bazillion times but unfortunately I cannot get past this. I am trying to load an image that is in my resources folder. When I use:

    public static BufferedImage[] readImages() {

       BufferedImage img = null;
       try { 
         img = ImageIO.read(new File("resources/imgs/map.png"));
       } catch (IOException e) {
       }

(see screenshot) and run the program, the image is loaded as it should. However, when I create the .jar file and try to run it, the image is not accessed and I get the error:

Exception in thread "main" java.lang.NullPointerException: src image is null at
java.desktop/java.awt.image.AffineTransformOp.filter(AffineTransformOp.java:214)
at MyClass.readImages(MyClass.java:100)
at MyClass.main(MyClass.java:21)

Then I try using the getResource() method, but that doesn't load the image and I get the NullPointerException error.

    public static BufferedImage[] readImages() {

       BufferedImage img = null;
       try { 
         img = ImageIO.read(MyClass.class.getClass().getClassLoader().getResource("resources/imgs/map.png"));
       } catch (IOException e) {
       }

Exception in thread "main" java.lang.NullPointerException
at MyClass.readImages(MyClass.java:92)
at MyClass.main(MyClass.java:21)

Does anyone have an idea on how to include the image to the .jar just by using "new File(filename)" or how to fix the NullPointerException?


EDIT: The solution to my problem was:

img = ImageIO.read(ClassLoader.getSystemClassLoader().getResourceAsStream("map.png"));

with map.jpg being in "MyProject/resources/map.jpg" and the script in "MyProject/src/MyClass.java".


0 Answers0