获取 BufferedImage 作为资源,以便它可以在 JAR 文件中工作 [英] Getting a BufferedImage as a resource so it will work in JAR file

查看:28
本文介绍了获取 BufferedImage 作为资源,以便它可以在 JAR 文件中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像作为 BufferedImage 加载到我的 java 应用程序中,目的是让它在 JAR 文件中工作.我尝试使用 ImageIO.read(new File("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") 在文件系统中寻找一个目录images,在当前目录下,这是启动应用程序的目录.所以这是错误的.

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 文件位于类路径中的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 将其编译"到其目标类目录,就会发生这种情况.为此,该文件必须与您的 Java 源文件一起位于源目录下.

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 文件中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆