java 从 .jar 文件中获取图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10489773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:17:05  来源:igfitidea点击:

Getting images from a .jar file

javaimagejarembedded-resource

提问by DCSoft

I need to get res folder to compile when I export a executable jar file in eclipse also when I use the getClass().getResource()method it doesn't work.

当我在 eclipse 中导出可执行 jar 文件时,我需要让 res 文件夹进行编译,当我使用getClass().getResource()它不起作用的方法时。

Current reading image code

当前读取图像代码

public Image loadImage(String fileName) {
    return new ImageIcon(fileName).getImage();
}

Code that doesn't work

不起作用的代码

public Image loadImage(String fileName) {
    return new ImageIcon(getClass().getResource(fileName).getImage();
}

采纳答案by DCSoft

I have now fixed the problem - this is the code that works

我现在已经解决了这个问题——这是有效的代码

 public BufferedImage loadImage(String fileName){

    BufferedImage buff = null;
    try {
        buff = ImageIO.read(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return buff;

}

The value of fileName is just an image name eg BufferedImage img = loadImage("background.png");

fileName 的值只是一个图像名称,例如 BufferedImage img = loadImage("background.png");

Thank you all for your help.

谢谢大家的帮助。

回答by Mattias Isegran Bergander

Either:

任何一个:

  • your path is wrong, you should get an error message if so, check it to see what path it actually tries, might not be what you think. Or debug and see what path it tries or even just print the path it tries.
  • 您的路径是错误的,如果是这样,您应该收到一条错误消息,检查它以查看它实际尝试的路径,可能不是您所想的。或者调试并查看它尝试的路径,甚至只是打印它尝试的路径。

or

或者

  • it's not in the jar. Check the jar file with a zip-program and/or rename it to have zip in the and open it to check that the file is really there.
  • 它不在罐子里。使用 zip 程序检查 jar 文件和/或将其重命名为 zip 并打开它以检查文件是否真的存在。