java显示存储在MySQL中的BLOB图像,无需写入磁盘
我有一个小程序,它将图片/图像文件作为BLOB存储在MySQL表中。 稍后,我需要能够在一个单独的JFrame中显示这个图像(已经得到了这个)
public static void showImage(File imageFile) {
JFrame f = new JFrame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
ImageIcon image = new ImageIcon(imageFile.getAbsolutePath());
JLabel lbl = new JLabel(image);
f.getContentPane().add(lbl);
f.setSize(image.getIconWidth(), image.getIconHeight());
int x = (screenSize.width - f.getSize().width) / 2;
int y = (screenSize.height - f.getSize().height) / 2;
f.setLocation(x, y);
f.setVisible(true);
}
我现在做的是:从MySQL中获取BLOB数据,创建一个本地(临时)文件,并在JFrame中显示
private void createFile() {
File imageFile = File.createTempFile("tmp-", ".jpeg", new File("./temp/"));
OutputStream out = null;
out = new FileOutputStream(imageFile);
Blob blob = new javax.sql.rowset.serial.SerialBlob((byte[]) grdGrid.getModel().getValueAt(row, grdGrid.getColumn("picture").getModelIndex()));
byte[] buff = blob.getBytes(1, (int) blob.length());
out.write(buff);
out.close();
showImage(imageFile);
}
有没有办法不用在磁盘上创建本地文件就可以做到这一点? 比如:
private void someMethod() { //just symbolic
Blob blob = MySQL.getBlob();
ImageIcon = blob.toImage();
}
谢谢你的帮助
# 1 楼答案
如图here所示,您可以从}
Blob
获取一个InputStream
并将其传递给^{