在jar文件中加载图像

时间:2013-08-31 11:45:57

标签: java image swing jar embedded-resource

我正在尝试从可执行的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());

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

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

  

/pictures/Logo1.png

这个当前代码既可以在eclipse中使用,也可以在导出到JAR并在终端中运行时使用,但在双击JAR时不起作用,在这种情况下,图标是默认的JFrame图标。

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

1 个答案:

答案 0 :(得分:2)

我曾经遇到过类似的问题,结果发现问题是相对的解决问题,而且我的路径在某种程度上处于错误的位置。我从我编写的一些旧代码中挖出这个代码,使其使用绝对路径。这似乎解决了我的问题;也许它会对你有用。

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