在jar文件中加载图像 [英] Load images in jar file
问题描述
我正在尝试从可执行的JAR文件加载图像。
这是检索图像的功能:
public static ImageIcon loadImage(String fileName,Object o){
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass()。getResource(fileName));
//也试过getResourceAsStream
} catch(IOException e){
e.printStackTrace();
返回null;
}
if(buff == null){
System.out.println(Image Null);
返回null;
}
返回新的ImageIcon(buff);
}
这就是它被调用的方式:
logo = FileConverter.loadImage(/ pictures / Logo1.png,this);
JFrame.setIconImage(logo.getImage());
此是一个简单的对象。
我也没有得到 NullPointerException ,除非它被UI屏蔽。
我检查了JAR文件和图片位于:
/pictures/Logo1.png
这个当前代码既可以在eclipse中使用,也可以在导出到JAR并在终端中运行时使用,但在双击JAR时不起作用,在这种情况下,图标是默认的JFrame图标。 / p>
谢谢你的帮助。可能只有我遗漏了一些明显的东西。
我曾经遇到类似的问题,结果发现问题是相对的问题不知何故,我的路径在错误的地方。我从我编写的一些旧代码中挖出这个代码,使其使用绝对路径。这似乎解决了我的问题;也许它适合你。
String basePath =(new File(。))。getAbsolutePath();
basePath = basePath.substring(0,basePath.length() - 1);
FileConverter.loadImage(basePath +/ pictures / Logo1.png,this);
I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
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);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object. I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
这篇关于在jar文件中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!