【问题标题】:Error in loading image - java.lang.IllegalArgumentException: input == null加载图像时出错 - java.lang.IllegalArgumentException: input == null
【发布时间】:2020-04-14 13:41:30
【问题描述】:

我尝试使用 Eclipse IDE 在 Java 中显示我的游戏项目的图像: 我有ImageReader:

public BufferedImage loadImage(String path) {
    try {
        BufferedImage image = ImageIO.read(getClass().getResource(path));
        return image;
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    return null;
}

我从GameWindow 类加载图像:

@Override
public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2D = (Graphics2D) g;

    g2D.drawImage(ImageReader.getInstance().loadImage("/x.png"), 0, 0, Game.FIELD_HEIGHT, Game.FIELD_WIDTH, null);
}

这是我的包资源管理器: Package Explorer

当我尝试运行程序时,我收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at game.util.ImageReader.loadImage(ImageReader.java:31)
at game.util.ImageReader.<init>(ImageReader.java:18)
at game.util.ImageReader.getInstance(ImageReader.java:24)
at game.gui.GameWindow.paint(GameWindow.java:31)

感谢任何帮助!

【问题讨论】:

    标签: java image


    【解决方案1】:

    您可能需要将图像读取代码更改为

    public BufferedImage loadImage(String path) {
    try {
        BufferedImage image = ImageIO.read( new FileInputStream( new File( path ) ) );
        return image;
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    return null;
    }
    

    我假设文件路径是正确的,并且您的 res 目录被正确标记为资源目录。

    【讨论】:

    • 如何知道我的文件路径是否正确以及 res 目录是否正确标记为资源目录?我尝试了您的解决方案,但不幸的是,我收到以下错误:java.io.FileNotFoundException: \0.png (系统找不到指定的文件)
    • 为什么像0.png?不应该是x.png吗??另外,我假设您没有正确设置资源根目录。尝试使用绝对文件路径而不是相对文件路径。例如:C://user/images/x.png 尝试stackoverflow.com/questions/36907204/… 并正确设置资源目录
    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2019-01-17
    • 1970-01-01
    • 2014-10-04
    • 2013-02-23
    • 2019-11-16
    相关资源
    最近更新 更多