簡體   English   中英

ImageIO.read() 返回 null 值

[英]ImageIO.read() returning a null value

我正在嘗試將字節數組轉換為bufferedImage以顯示在jLabel中,但ImageIO.read()屬性返回 null 值,因此返回NullPonterException 我應該怎么辦?

 InputStream input = new ByteArrayInputStream(array);
    try {
     BufferedImage bufer = ImageIO.read(input);
     ImageIcon icon=new ImageIcon(new ImageIcon(bufer).getImage().getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), Image.SCALE_SMOOTH));
       
        jLabel3.setIcon(icon);
    } catch (IOException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    }`

根據javadocread(InputStream)方法...

“返回BufferedImage作為解碼提供的InputStream的結果,其中ImageReader從當前注冊的那些中自動選擇InputStream包裝在ImageInputStream中。如果沒有注冊的ImageReader聲稱能夠讀取生成的 stream,則返回null

最后一句話很可能解釋了您的問題。


我應該怎么辦?

所以你解決這個問題的方法是:

  1. 檢查array的內容是否符合您的預期。
  2. 確定它是哪種圖像格式,以及它是否正確表示。 例如,如果圖像存儲在數據庫中或通過網絡請求發送,請確保它沒有在此過程中被破壞。
  3. 檢查它是否是受支持的圖像格式; 應該有一個注冊的ImageReader class 。

感謝您幫助我解決問題,我將在此處發布回復以幫助其他人。

1.對數據庫(postgresql)的查詢必須是preparedStatement,因為如果您保存轉換為byte []的圖像,則此聲明為您提供setBinaryStream功能,當您檢索它並將其添加到byte []中時,沒有任何變化

   ////This way save the image and his path (the last is optional)
    JFileChooser f = new JFileChooser();
    f.showOpenDialog(null);
    File file = f.getSelectedFile();
    FileInputStream s = null;
    String path = file.getAbsolutePath();
 try {
    s = new FileInputStream(file);
            Conexion();
            PreparedStatement pq = conexion.prepareStatement("INSERT INTO prueba(foto, cam) VALUES (?, ?);");
            pq.setBinaryStream(1, s, (int) file.length());
            pq.setString(2, path);
            pq.executeUpdate();
            s.close();
      } catch (ClassNotFoundException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        }



   /////This way retrive the info
   byte[] array = null;
   String photopath = "";
   try {
        Conexion();
        PreparedStatement p = conexion.prepareStatement("SELECT foto, cam FROM prueba;");
        ResultSet sq = p.executeQuery();
        while (sq.next()) {
            array = sq.getBytes("foto");
            photopath = sq.getString("cam");
            //jLabel3.setIcon(new ImageIcon(array));

            break;
        }
        sq.close();
        p.close();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    }

    ImageIcon icon=new ImageIcon(array);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM