Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a BufferedImage as a resource so it will work in JAR file

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.

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.

Am I missing something here?

like image 301
fvgs Avatar asked Jun 09 '13 07:06

fvgs


People also ask

Do JAR files contain resources?

A JAR (Java ARchive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file for distribution. JAR files are archive files that include a Java-specific manifest file.

What is the difference between BufferedImage and image?

List, the difference between Image and BufferedImage is the same as the difference between List and LinkedList. Image is a generic concept and BufferedImage is the concrete implementation of the generic concept; kind of like BMW is a make of a Car. Show activity on this post. Image is an abstract class.

How do I find the size of a BufferedImage?

Before you load the image file as a BufferedImage make a reference to the image file via the File object. File imgObj = new File("your Image file path"); int imgLength = (int) imgObj. length(); imgLength would be your approximate image size though it my vary after resizing and then any operations you perform on it.


1 Answers

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() 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.

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"));

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.

like image 197
JB Nizet Avatar answered Sep 24 '22 02:09

JB Nizet