Trying to load an image using ImageIO.read (class.getResource (URL)), but getResource returns null

I am making a 2D game with my buddy and I learned a lot about some basic game concepts in some Youtube tutorials. One of the things I studied is sprites (for those who don’t know the 2D images to display on the screen) and how to use them in my game. I used ImageIO.read(this.class.getResource(pathToMySprite)) , but it seems that getResource() for some reason returns null .

I distorted the path a bit, adding a β€œ/” in front of it, removing the β€œ/”, placing the user.dir property to see if it needs the whole path, and I still get the same error.

 TILE_TEXTURES(System.getProperty("user.dir") + "/textures/tile.png"); //ENTITY_TEXTURES("/textures/entity.png"); private BufferedImage img; private SpriteSheet(String path) { System.out.println(System.getProperty("user.dir")); try { //TODO: Fix this error, don't know what wrong. img = ImageIO.read(SpriteSheet.class.getResource(path)); // error here!!! } catch (IOException e) { e.printStackTrace(); } } public BufferedImage getImage() { return img; } 

Any help is appreciated. I haven’t commented on the code (usually I do it when I can find a place where I can sit back and be happy with what I finished), but this is a pretty small class, so I think you guys can figure out that everything is in order.

A folder containing an IS image in the class path of my project. I also included an error:

 Exception in thread "Thread-2" java.lang.ExceptionInInitializerError at com.brickbattle.client.src.gui.Sprite.<clinit>(Sprite.java:7) at com.brickbattle.client.src.objs.Tile.<init>(Tile.java:67) at com.brickbattle.client.src.objs.Player.initPlayerNum(Player.java:19) at com.brickbattle.client.src.util.BrickBattle.init(BrickBattle.java:114) at com.brickbattle.client.src.util.BrickBattle.run(BrickBattle.java:85) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.IllegalArgumentException: input == null! //HERE IS ERROR at javax.imageio.ImageIO.read(Unknown Source) at com.brickbattle.client.src.gui.SpriteSheet.<init>(SpriteSheet.java:17) at com.brickbattle.client.src.gui.SpriteSheet.<clinit>(SpriteSheet.java:8) 

Thanks again!

+4
source share
1 answer

This issue is mostly not related to ImageIO, but rather Class / ClassLoader.getResource or getResourceAsStream .

See this answer for clarification.

In any case, these methods of obtaining the resource will be read-only from the class class (i.e. user.dir will never help here).

This should work:

 ImageIO.read(getClass().getResource("/path/to/resource")); 

If the path refers to the root of the class path (indicated by the leading /).

If your resources are not in the classpath, just use:

 ImageIO.read(new File("path/to/resource"); 

If the path refers to the directory from which your application was launched.

+5
source

Source: https://habr.com/ru/post/1485211/


All Articles