【问题标题】:Load images in jar file将图像加载到 jar 文件中
【发布时间】:2013-09-04 01:28:06
【问题描述】:

我正在尝试从可执行 JAR 文件加载图像。

我关注了here的信息,然后是here的信息。

这是检索图像的函数:

public static ImageIcon loadImage(String fileName, Object o) {
     BufferedImage buff = null;
     try {
        buff = ImageIO.read(o.getClass().getResource(fileName));
        // Also tried getResourceAsStream
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    if (buff == null) {
        System.out.println("Image Null");
        return null;
    }
    return new ImageIcon(buff);
}

这就是它的名称:

logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());

this 是一个简单的对象。 我也没有得到 NullPointerException,除非它被 UI 屏蔽。

我检查了 JAR 文件,图像位于:

/pictures/Logo1.png

当前代码在 eclipse 中和导出到 JAR 并在终端中运行时都有效,但在双击 JAR 时无效,在这种情况下,图标是默认的 JFrame 图标。

感谢您的帮助。可能只有我遗漏了一些明显的东西。

【问题讨论】:

  • 即使我双击JAR 文件或通过command prompt 运行它,它在我这边也能正常工作。我在 eclipse juno 中创建了 this project,你也可以测试一下 :-)
  • 如果你直接这样做 - return new ImageIcon(getClass().getResource("/pictures/Logo1.png")); 会发生什么?

标签: java image swing jar embedded-resource


【解决方案1】:

我曾经遇到过类似的问题,结果证明是相对寻址问题以及我的路径不知何故位于错误的位置。我从我写的一些旧代码中挖出了这个,使它使用绝对路径。这似乎解决了我的问题;也许它会为你工作。

String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this); 

【讨论】:

  • 这导致完整的文件名是/Geometric Shapes//pictures/Logo1.png,抱歉回复晚了
  • 我修好了,问题出在我操作系统上的 java 上。无论如何感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多