java 获取 BufferedImage 作为资源,以便它可以在 JAR 文件中工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17007448/
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
Getting a BufferedImage as a resource so it will work in JAR file
提问by fvgs
I'm trying to load an image into my java application as a BufferedImage, with the intent of having it work in a JAR file. I tried using ImageIO.read(new File("images/grass.png"));
which worked in the IDE, but not in the JAR.
我正在尝试将图像作为 BufferedImage 加载到我的 java 应用程序中,目的是让它在 JAR 文件中工作。我尝试使用ImageIO.read(new File("images/grass.png"));
which 在 IDE 中有效,但在 JAR 中无效。
I've also tried
我也试过
(BufferedImage) new ImageIcon(getClass().getResource(
"/images/grass.png")).getImage();
which won't even work in the IDE because of a NullPointerException. I tried doing it with ../images, /images, and images in the path. None of those work.
由于 NullPointerException,它甚至无法在 IDE 中工作。我尝试使用路径中的 ../images、/images 和图像来执行此操作。这些都不起作用。
Am I missing something here?
我在这里错过了什么吗?
回答by JB Nizet
new File("images/grass.png")
looks for a directory images on the file system, in the current directory, which is the directory from which the application is started. So that's wrong.
new File("images/grass.png")
在文件系统上查找目录images,在当前目录中,即应用程序启动的目录。所以这是错误的。
ImageIO.read()
returns a BufferedImage, and takes a URL or an InputStream
as argument. To get an URL of InputStream
from the classpath, you use Class.getResource()
or Class.getResourceAsStream()
. And the path starts with a /, and starts at the root of the classpath.
ImageIO.read()
返回一个 BufferedImage,并接受一个 URL 或一个InputStream
作为参数。要从InputStream
类路径中获取 的 URL ,请使用Class.getResource()
或Class.getResourceAsStream()
。路径以 / 开头,从类路径的根开始。
So, the following code should work if the grass.png file is under the package images
in the classpath:
因此,如果grass.png 文件images
位于类路径中的包下,则以下代码应该可以工作:
BufferedImage image = ImageIO.read(MyClass.class.getResourceAsStream("/images/grass.png"));
This will work in the IDE is the file is in the runtime classpath. And it will be if the IDE "compiles" it to its target classes directory. To do that, the file must be under a sources directory, along with your Java source files.
如果文件位于运行时类路径中,这将在 IDE 中起作用。如果 IDE 将其“编译”到其目标类目录,就会发生这种情况。为此,该文件必须与 Java 源文件一起位于源目录下。