【问题标题】:Can´t load image from package无法从包中加载图像
【发布时间】:2016-11-28 04:48:53
【问题描述】:

我的问题是我无法使用 maven 从我的 java 项目中的子包加载图像。

This is my project structure

我尝试了一些不同的代码 sn-ps,但总是得到一个 Nullpointer 异常。

我试过了:

Image image = new Image("/frontend/pictures/logo.png");
Image image = new Image("frontend/pictures/logo.png");
Image image = new Image("pictures/logo.png");
Image image = new Image(getClass().getResource("frontend/pictures/logo.png").toString());

在另一个项目中它对我来说很好,但现在我不知道我做错了什么。

感谢您的帮助。

【问题讨论】:

  • Image 类在哪个包中具有构造函数的参数?
  • 你在这里使用哪个Image 类? java.awt.Image 只有一个无参数构造函数,它是 >>JavaImage 类。
  • 对不起,我忘了说我使用 javafx。

标签: java image maven resources package


【解决方案1】:

这是我使用 ImageIcons 创建的一个不错的图像加载方法:

public Image img(String path) {
    ImageIcon icon = new ImageIcon(path);
    return icon.getImage();
}

然后,当您希望加载图像时,只需使用:

Image image = img("frontend/pictures/logo.png") 

这应该有效。 请注意,如果您想使用可运行的 JAR,则必须使用此实现:

static Image setImage(String path) {
    Image tmp = null;
    try {
        tmp = ImageIO.read(/*Class name*/.class.getResourceAsStream(path));
    } catch (IOException e){
        e.printStackTrace();
    }
    return tmp;
}

并输入:

Image image = setImage("/org/.../logo.png");

将您的图像放在 JAR 的 org 文件夹内的某个子文件夹中。

【讨论】:

    【解决方案2】:

    我忘了说我使用 JavaFX 是我的错。 但我解决了我的问题。

    我将图片目录添加为资源文件夹,然后:

    Image img = new Image(getClass.getRessource("/logo.png").toString);
    

    感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 2016-10-12
      • 2015-07-25
      • 2018-04-05
      • 2013-01-11
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多