问题描述
我正在尝试将图像作为BufferedImage加载到我的java应用程序中,目的是让它在JAR文件中工作。我尝试使用 ImageIO.read(新文件(images / grass.png));
在IDE中工作,但在JAR中没有。
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) new ImageIcon(getClass().getResource(
"/images/grass.png")).getImage();
由于NullPointerException,它甚至不能在IDE中工作。我尝试使用../images,/ images和路径中的图像。这些都不起作用。
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.
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
new File(images / grass.png)
在当前目录中查找文件系统上的目录映像,该目录是启动应用程序的目录。所以这是错误的。
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.
ImageIO.read()
返回一个BufferedImage,并获取一个URL或 InputStream
作为参数。要从类路径获取 InputStream
的URL,请使用 Class.getResource()
或 Class.getResourceAsStream()
。路径以/开头,并从类路径的根开始。
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.
因此,如果grass.png文件位于包<
下,则以下代码应该有效类路径中code> images :
So, the following code should work if the grass.png file is under the package images
in the classpath:
BufferedImage image = ImageIO.read(MyClass.class.getResourceAsStream("/images/grass.png"));
这将在IDE中工作,文件位于运行时类路径中。如果IDE将其编译到其目标类目录,那将是它。为此,该文件必须与源目录一起位于源目录下。
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.
这篇关于获取BufferedImage作为资源,以便它可以在JAR文件中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!