Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试读取图像并获取空指针异常_Java_Image - Fatal编程技术网

Java 尝试读取图像并获取空指针异常

Java 尝试读取图像并获取空指针异常,java,image,Java,Image,我正在尝试读取图像并将其存储为整数数组,以便在屏幕上显示它。我不知道是什么原因导致我的代码返回这个空指针异常,我希望有人能解释一下 以下是加载方法的代码: import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; public class TextureUI { private int width = 800, height = 600; pu

我正在尝试读取图像并将其存储为整数数组,以便在屏幕上显示它。我不知道是什么原因导致我的代码返回这个空指针异常,我希望有人能解释一下

以下是加载方法的代码:

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

import javax.imageio.ImageIO;

public class TextureUI {

    private int width = 800, height = 600;
    public int[] pixels = new int[width*height];

    public void load(String path) {
        try {
            BufferedImage image = ImageIO.read(TextureUI.class.getResource(path));
            int w = width;
            int h = height;
            image.getRGB(0, 0, w, h, pixels, 0, w);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
我在这里使用它:

private Render ui;
private TextureUI texui;

public Screen(int width, int height) {
    super(width, height);
    ui = new Render(width, height);
            //Here is where my code is null pointing 
    texui.load("ui/hands.png"); // < That function call
    for (int i = 0; i < (width * height); i++) {
        ui.pixels[i] = texui.pixels[i];
    }
}
私有渲染ui;
私用纺织品;
公共屏幕(整数宽度、整数高度){
超级(宽度、高度);
ui=新渲染(宽度、高度);
//这里是我的代码指向空的地方
load(“ui/hands.png”);//<该函数调用
对于(int i=0;i<(宽度*高度);i++){
ui.pixels[i]=texui.pixels[i];
}
}
有人能解释一下为什么会发生这种错误吗?

如果路径

ui/hands.png
相对于类路径的,则应将其更改为

/ui/hands.png
如果为
类#getResource(String)
方法提供了一个没有前导
/
的路径,它将使用调用它的
类的包。例如,如果
TextureUI
在包
com.graphics
中,那么Java将在中查找资源

com/graphics/ui/hands.png
相对于类路径的根


更详细地解释了它。

您的texui属性为null(未实例化),您尝试从中调用方法。您应该在调用texui的“load”方法之前实例化它

将以下代码放入屏幕构造函数中:

texui = new TextureUI();
texui.load("ui/hands.png"); 

您应该发布stacktrace。下面@leblma和[at]Sotirios Delimanolis的答案都应该考虑,因为它们都包含一个有效的参数。我尝试了这个方法,但现在ImageIO.read函数返回了一个IllegalArgumentException。当您遇到异常时,您应该发布stacktrace。我想你应该看看索蒂里奥斯的答案,它可能会解决你的问题