简体   繁体   中英

Error in loading image - java.lang.IllegalArgumentException: input == null

I try to display image for my game project in Java, using Eclipse IDE: I have the 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;
}

I load the image from the GameWindow class:

@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);
}

This is my Package Explorer: Package Explorer

When I try to run the program I receive the following error:

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)

Thanks to any help!

You may have to change the image read code as

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;
}

I assume for filepath is correct and your res directory is marked as the resource directory properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM