ImageIO.read返回NULL,没有错误 [英] ImageIO.read returns NULL, with no errors
问题描述
以下代码似乎不起作用,即使文件看起来很好。
The following code seems not to work, even though the file appears to be found just fine.
images = new BufferedImage[32];
FileInputStream fis = null;
for (int i = 0; i < 32; i++) {
File file = new File("tiles\\"+i+".bmp");
if (!file.exists()){
System.out.println("File "+i+" failed");
}
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.err.println(e + "" + i);
}
try {
images[i] = ImageIO.read(fis);
} catch (IOException e) {
System.err.println(e + "" + i);
}
if (images[i] == null) {
System.out.println("Image "+i+" failed");
}
}
提前感谢您的帮助。
编辑:结果是我尝试使用Graphics.drawImage(images [0]);,它给我一个空指针异常。此代码在此处完成。
The result is me attempting to Graphics.drawImage(images[0]);, and it giving me a null pointer exception. This code here completes fine.
编辑:已更改按照建议移动了if(!file.exists()),并将文件包装在输入流中。
Changed moved the if(!file.exists()) as suggested, and wrapped the file in an input stream.
推荐答案
ImageIO.read(file); 如果没有注册 ImageReader 将返回null找不到。请检查您是否注册了 ImageReader 。
ImageIO.read(file); will return null if no registered ImageReader is not found. Please check whether you have registered any ImageReader or not.
我认为此代码段可以帮助您
I think this code snippet could help you
File file = new File("bear.jpg"); // I have bear.jpg in my working directory
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis); //reading the image file
您只需将文件包装成 FileInputStream 然后将其传递给读取()
You just need to wrap the file into an FileInputStream and then pass it to read()
这篇关于ImageIO.read返回NULL,没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!