iT邦幫忙

0

想請問java code 如何取得資料庫BLOB照片檔 和我在那裡寫錯

(https://ithelp.ithome.com.tw/upload/images/20201008/20130856M3S9UmNxwP.jpg)

MY Code:

JButton btnNewButton = new JButton("Show");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName(sDriver);
} catch (ClassNotFoundException e1) {
System.out.print("fail");
}
try {
dbCon = DriverManager.getConnection(sCon,username, password);
String sql = "Select * from test ";
ps = (PreparedStatement) dbCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i = 0;
while(rs.next()) {
String ID = rs.getString("ID");
Blob image = rs.getBlob("photo");
tbModel = (DefaultTableModel) table.getModel();
Object tData[] = {ID ,image};
tbModel.addRow(tData);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2020-10-08 22:23:07
Blob imageBlob = resultSet.getBlob("photo");
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
Image image = ImageIO.read(binaryStream);

參考資料一
參考資料二

另外,點這裡是我這次鐵人賽唯一的一篇文章,喜歡的話左上角點 Like

剛有測試你的用法 但是我JTable好像還是無法呈現圖片
他這次呈現BufferedImage@509a5207: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@fe97666 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 50 height = 50 #numDataElements 3 dataOff[0] = 2
變成資訊的樣子
我是有連資料庫 資料id 和image已經事先匯進去
只是想要讀取的時候能呈現在Jtable
測試過很多方式好像都沒辦法呈現圖片
我貼我完整code你有空可以幫我看看嗎?/images/emoticon/emoticon02.gif
https://pastebin.com/Kj4AvdVk

先確定抓出來的是圖片
加上以下代碼將圖片存成檔案

BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);

// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();

ImageIO.write(bimage, "png", new File("./test.png"));

如果圖片正確,就去找「如何將圖片放進 DefaultTableModel
如果圖片錯誤,就回頭檢查 MySql 裡的圖片資料正確性

https://stackoverflow.com/questions/31631299/how-to-display-a-picture-in-a-jtable
網路上找了很多但都碰壁:(
我有試過這方法 但得到結果跟一開始一樣

我要發表回答

立即登入回答