[英]ImageIO.read returns NULL, with no errors
以下代碼似乎不起作用,即使該文件似乎找到得很好。
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]);,它給了我一個 null 指針異常。 這里的代碼完成得很好。
編輯:按照建議更改了 if(.file,exists()) 的移動。 並將文件包裝在輸入流中。
ImageIO.read(*...)
將只加載這些圖像類型GIF 、 PNG 、 JPEG 、 BMP和WBMP 。
任何其他圖像類型都將無錯誤地返回null
。
參考:http ://docs.oracle.com/javase/tutorial/2d/images/loadimage.html
我確實意識到這不是特定原始問題的解決方案,而是所提出問題的解決方案。
ImageIO.read(文件); 如果未找到已注冊的ImageReader,則返回 null。 請檢查您是否已注冊任何ImageReader 。
我認為這個代碼片段可以幫助你
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 中,然后將其傳遞給read()
嘗試將您的 InputStream 包裝到 BufferedInputStream 中:
fis = new FileInputStream(file); ==> new BufferedInputStream(new FileInputStream(file));
使用new File(getClass().getResource("tiles\\\\"+i+".bmp"));
添加以下依賴項:
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-jpeg2000</artifactId>
<version>1.4.0</version>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.