1
我正在使用mysql
作爲我的數據庫。我得到我的Java代碼中的字節數組。然後我將這個字節數組作爲LONGBLOB
存儲在數據庫中。現在,當檢索它從數據庫回來,我使用下面的代碼:無法將字節數組轉換爲緩衝圖像
package com.sendSms;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
public class SampleTest {
public Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/forTest","root","123456");
}catch(Exception ex){}
return con;
}
public byte[] getFromDb(){
byte[] arr=null;
try{
Connection con = getConnection();
PreparedStatement pstmt=con.prepareStatement("select id,image from TestAndroid where id = ?");
pstmt.setInt(1, 16);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
// int id=rs.getInt("id");
arr = rs.getBytes("image");
}
}
catch(Exception ex){ex.printStackTrace();}
return arr;
}
public void go() throws IOException{
byte[] arr=getFromDb();
InputStream is=new ByteArrayInputStream(arr);
BufferedImage bi= ImageIO.read(is);
if(bi==null){
System.out.println("bi is NULL");
}
else{
System.out.println("bi is NOT NULL");
}
}
public static void main(String[] args) throws IOException {
SampleTest st = new SampleTest();
st.go();
}
}
當我運行這段代碼我得到BufferedImage
爲空;儘管此時字節數組不爲空。如何得到這個BufferedImage
。我需要BufferedImage
,因爲我需要將它傳遞給其他函數,只接受BufferedImage。我該如何解決這個問題。
另外存儲字節數組中分貝時,我使用:
setBytes(byte array)
方法對db PreparedStatement
&我使用LONGBLOB
數據類型存儲該字節數組。
答案取決於你如何將圖像寫入數據庫 – MadProgrammer
這就是我所說的:我在'PreparedStatement'上使用'setBytes(byte [])'。在db中它的'Longblob'數據類型。 – JPG
如何首先獲取圖像字節?從文件或「BufferedImage」? – MadProgrammer