简体   繁体   English

如何从 jar 文件加载图像?

[英]How to load the image from a jar file?

This code works only if I run my project, but if I run the Jar file, I get a NullPointerException.此代码仅在我运行我的项目时才有效,但如果我运行 Jar 文件,我会收到 NullPointerException。 The image is in src directory.该图像位于 src 目录中。

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.如果我使用此代码,则会引发 IllegalArgumentException。

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?如何加载图像?

You did say the PNG is in the src folder?您确实说过 PNG 在src文件夹中?

Let's see, after reading this and this , I think it needs to be:让我们看看,读完thisthis后,我认为它需要是:

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

or或者

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

Think unix, not windows.想想 unix,而不是 windows。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM