[英]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);
}`
根據javadoc , read(InputStream)
方法...
“返回
BufferedImage
作為解碼提供的InputStream
的結果,其中ImageReader
從當前注冊的那些中自動選擇InputStream
包裝在ImageInputStream
中。如果沒有注冊的ImageReader
聲稱能夠讀取生成的 stream,則返回null
。 “
最后一句話很可能解釋了您的問題。
我應該怎么辦?
所以你解決這個問題的方法是:
array
的內容是否符合您的預期。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.