【问题标题】:Input == null with using ImageIO.read [duplicate]使用 ImageIO.read 输入 == null [重复]
【发布时间】:2017-11-24 16:23:03
【问题描述】:

这是我正在使用的代码:

/**
 * This method loads an image
 * 
 * @param path - path of the image
 * 
 * 
 */
public static BufferedImage loadImage(String path) {
    try {
        return ImageIO.read(ImageLoader.class.getClass().getResourceAsStream(path));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
    return null;
}

这是错误:

线程“Thread-2”中的异常 java.lang.IllegalArgumentException: 输入 == null!
在 javax.imageio.ImageIO.read(未知来源)
在 io.deadspace.graphics.ImageLoader.loadImage(ImageLoader.java:19)
在 io.deadspace.graphics.asset.assets.EntityAssets.initEntityAssets(EntityAssets.java:15)
在 io.deadspace.graphics.asset.Assets.init(Assets.java:37)
在 io.deadspace.Game.init(Game.java:73)
在 io.deadspace.Game.run(Game.java:127)
在 java.lang.Thread.run(Unknown Source)

我最近重做了将图像加载到游戏中的方式,以前效果很好,但现在,它不再有效了。我已经尝试过 getResource 和 getResourceAsStream。

以下是我如何加载图像的一些示例:

public void initEntityAssets() {
    sheet = new SpriteSheet(ImageLoader.loadImage("res/textures/sheet.png"));

    wood = sheet.crop(width, height, width, height);
    tree = sheet.crop(0, 0, width, height * 2);
    rock = sheet.crop(0, height * 2, width, height);
    rockDropItem = sheet.crop(1, height * 2, width, height);

}

public void initHotbarAssets() {
    sheet = new SpriteSheet(ImageLoader.loadImage("res/textures/sheet.png"));

    hotbar = sheet.crop(0, height * 4, width, height);
    hotbar_selected = sheet.crop(0, height * 5, width, height);
}

【问题讨论】:

  • 还可以考虑加载一次图像并重复使用它。

标签: java


【解决方案1】:

你的路径应该是相对于类路径根的,所以它应该是

sheet = new SpriteSheet(ImageLoader.loadImage("/res/textures/sheet.png"));

【讨论】:

    【解决方案2】:

    如果 res 位于项目结构的 java 文件夹中,则必须使用:

     ImageLoader.class.getClassLoader().getResourceAsStream(path)
    

    原因在这里描述:

    Difference between getClass().getClassLoader().getResource() and getClass.getResource()?

    另一个替代使用 getClassLoader() 的解决方案是在路径中添加一个斜杠,以便它开始在根路径中搜索。

    /res/something
    

    而不是 res/something

    【讨论】:

    • 这修复了它!非常感谢!!
    • 请点赞或接受答案
    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 2014-11-08
    • 2016-05-28
    • 1970-01-01
    • 2015-05-13
    • 2021-12-15
    相关资源
    最近更新 更多