2012-03-30 148 views
15

下面的代碼似乎不起作用,即使該文件看起來很好。ImageIO.read返回NULL,沒有錯誤

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(圖像[0]);;它給了我一個空指針異常。這裏的代碼完成很好。

編輯:更改按照建議移動了if(!file.exists()),並將該文件包裝在輸入流中。

+3

[RTFM](http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#read%28java.io.File%29) – mre 2012-03-30 13:34:47

+0

你能描述一下結果嗎?一個瘋狂的猜測:在不正確的路徑... – 2012-03-30 13:36:59

+0

爲什麼你不把你的測試,如果(!file.exists())System.out.println(「文件」+ i +「失敗」);在讀之前是否有 ? – 2012-03-30 13:38:37

回答

7

ImageIO.read(file);如果沒有註冊,將返回null ImageReader找不到。請檢查您是否註冊了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,然後將它傳遞給閱讀()

+0

我可能仍然沒有正確地做到這一點,但我所做的卻是失敗。我更改了上面的代碼以顯示更改內容。 – Naberius 2012-03-30 13:59:19

+0

你能說出你的磁盤中有什麼圖像文件名嗎? – 2012-03-30 14:07:37

+0

@Naberius你能說你的磁盤中有什麼圖像文件名?這完全符合我的情況。 – 2012-03-30 14:16:14

0

嘗試換你的InputStream到的BufferedInputStream:

FIS =新的FileInputStream(文件); ==> new BufferedInputStream(new FileInputStream(file));

相關問題