-1

This code works only if I run my project, but if I run the Jar file, I get a NullPointerException. The image is in src directory.

try {
            URL resource = Sticker.class.getResource("\\transparentSticker.png");
            img = null;
            this.img = ImageIO.read(Paths.get(resource.toURI()).toFile());
            System.out.println("c");
        } catch (IOException | URISyntaxException e) {
            System.out.println("caught");
        }

If I use this code, an IllegalArgumentException is being thrown.

InputStream input = Sticker.class.getResourceAsStream("\\transparentSticker.png");
        if (input == null) {
          
            input = Sticker.class.getClassLoader().getResourceAsStream("\\transparentSticker.png");
        }
            try {
                img = ImageIO.read(input);
            } catch (IOException e) {
                e.printStackTrace();
            }

How to load the image?

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 2
    1) not sure why you are using the Paths class. The ImageIO.read(...) method will accept a URL as a parameter 2) did you include the file in your .jar file? – camickr May 16 '21 at 19:06
  • The argument to getResource and getResourceAsStream is not a filename, it’s a URL. The backslash is not a legal character in a URL. You probably meant `"/transparentSticker.png"`. Also, as camickr said, don’t try to convert the URL to a file; just load the URL directly. – VGR May 17 '21 at 22:25

1 Answers1

0

You did say the PNG is in the src folder?

Let's see, after reading this and this, I think it needs to be:

InputStream input = Sticker.class.getResourceAsStream("/src/transparentSticker.png");

or

URL resource = Sticker.class.getResource("/src/transparentSticker.png");

Think unix, not windows.

Kevin
  • 398
  • 2
  • 7