Reputation: 3177
I don't know why in Java it should be so complicated, but I've already spent a good few hours on this. I have a png image in \src\resources\resize-cursor.png
Now, I want to use this image with BufferedImage
class
BufferedImage myPicture = null;
try {
// this is just one of the examples I tried... I've already tried like 10 ways to achieve this but I am always getting NullReferenceException
myPicture = ImageIO.read(getClass().getResourceAsStream("\\resources\\resize-cursor.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is there a one working way just to link the png resource in my app?
Upvotes: 0
Views: 1795
Reputation: 51
I believe the problem is that you are using 2 slashes and they are the wrong way. Use this "/" instead of "\" or "\". Also it may help if you have made your resource folder a class folder.
Here are 2 links if you like some more information: 1. Oracle tutorial on BufferedImage 2. Documentation of BufferedImage
The way i like to load images is to make a class to make it more simple like this.
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImages(String path) {
try { image = ImageIO.read(getClass().getResource(path)); }
catch (IOException e) { e.printStackTrace(); }
return image;
}
}
And to load a "bufferedImage" using this.
BufferedImageLoader loader = new BufferedImageLoader();
image1 = loader.loadImages("/image1.png");
image2 = loader.loadImages("/image2.png");
Upvotes: 0
Reputation: 109557
Open the jar with 7zip or you maybe can open it in the IDE.
Then search the file. My guess: /resources is the top directory.
myPicture = ImageIO.read(getClass().getResourceAsStream("/resize-cursor.png")));
Use slash /
for a case-sensitive path.
Make sure that the class of getClass()
is in the same jar. Think what inheritance might do.
You can do too:
myPicture = ImageIO.read(ClassInJar.class.getResourceAsStream("/resize-cursor.png")));
Upvotes: 0
Reputation: 91
Have you tried getClass().getResourceAsStream("/resources/resize-cursor.png")
?
Upvotes: 1