首页 > 解决方案 > 如何修复使用 ImageIO.read [Java] [初学者] 加载纹理时出现的错误

问题描述

我最近决定尝试在远离 Java 多年后重新回到 Java,并且正在关注制作游戏的 youtube 教程系列。我尝试加载使用以下代码制作的纹理(我正在使用 Eclipse)

public static Render plane = loadBitmap("/textures/floor.png");

public static Render loadBitmap(String fileName) {
    try {
        BufferedImage image = ImageIO.read(Texture.class.getResourceAsStream(fileName));
        int width = image.getWidth();
        int height = image.getHeight();
        Render result = new Render(width, height);
        image.getRGB(0,  0, width, height, result.pixels, 0, width);
        return result;
    }catch (Exception e) {
        Debug.logError("CRASH | Failed to load image");
        throw new RuntimeException(e);
    }
}

我收到以下错误:

Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException: input == null!
at net.xernia.bluehero.graphics.Texture.loadBitmap(Texture.java:23)
at net.xernia.bluehero.graphics.Texture.<clinit>(Texture.java:11)
... 5 more
Caused by: java.lang.IllegalArgumentException: input == null!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1356)
at net.xernia.bluehero.graphics.Texture.loadBitmap(Texture.java:15)
... 6 more

我的项目结构如下:

 src
     package
         Texture.java
 res
     textures
         floor.png

我在 Properties->java build path 下添加了 res 作为 modulepath 下的类文件夹。抱歉,如果这对你们中的某些人来说是一个非常微不足道的错误,但这让我感到困惑,哈哈。希望这是足够的信息,如果我遗漏了一些重要的信息,请告诉我:)

标签: javatexturesjavax.imageio

解决方案


将文件夹 res 移动到 src,我们有:

src
    package
         Texture.java
    res
         textures
             floor.png

并将文件名更改为/res/textures/floor.png. (不要忘记重建项目)


推荐阅读