-3

嗨,我遇到了一个烦人的错误,当无法加载图像时,它不断地给我输入 == null 错误。这是代码。

  package Graphics;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class spritesheet {
    public String path;
    public int width;
    public int height;
    public int[] pixels;


        public spritesheet(String path){
            BufferedImage image = null;

            try {
                image =
                        ImageIO.read(spritesheet.class.getResourceAsStream(path));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(image == null){
                return;
            }
            this.path = path;
            this.width = image.getWidth();
            this.height = image.getHeight();

            pixels = image.getRGB(0, 0, width, height, null ,0  , width);
        }           
        public int[][] getsprite(int x, int y, int[][] pixels){
            int i = 0;
            for(int xx = 0;xx< 7;x++){
                for(int yy = 0; yy< 7;yy++){
                    pixels[xx][yy] = this.pixels[i];
                    i++;
                }
            }
            return pixels;
        }
    }   

我检查过,目录完全正确。

错误

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at Graphics.spritesheet.<init>(spritesheet.java:20)
    at Tile.Tile.<init>(Tile.java:9)
    at Tiles.Wall.<init>(Wall.java:8)
    at Tiles.tiles.<init>(tiles.java:6)
    at Core.core.<init>(core.java:27)
    at Core.core.main(core.java:140)
4

1 回答 1

1

用于FileImageInputStream读取您的文件

ImageIO.read(new FileImageInputStream(new File(path)));

因为,您使用绝对路径(C:\test.png)不要使用getresourceAsStream()which 用于从您的classpath加载资源。其次,您不需要在路径中转义正斜杠。使用C:/testfile.pngC:\\testfile.png

参考:
ImageIO#read(javax.imageio.stream.ImageInputStream)

于 2013-07-04T19:54:37.543 回答