0

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?

inside
  • 3,047
  • 10
  • 49
  • 75
  • 1
    It looks like the slash orientation is in the opposite direction. Try doing this: `"/resources/resize-cursor.png"`. I don't know if this will work, which is why I'm leaving it as a comment. When I've loaded in assets through `getResourceAsStream`, this is how I've always done it. – rayryeng Sep 11 '14 at 16:06
  • Did you try myPicture = ImageIO.read(getClass().getResourceAsStream("/resize-cursor.png"))) ? – Xavier Delamotte Sep 11 '14 at 16:06
  • 1
    The JavaDoc is pretty explicit on that: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String) , so I guess rayryeng is correct. – Fildor Sep 11 '14 at 16:10

3 Answers3

1

Have you tried getClass().getResourceAsStream("/resources/resize-cursor.png")?

Fraser
  • 91
  • 8
0

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")));
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

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