从PostgreSQL数据库中显示图像,bytea [英] Displaying image from PostgreSQL database, bytea
本文介绍了从PostgreSQL数据库中显示图像,bytea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码拍摄图片test.gif并将图片位值放入bytea coloumn。
This code takes picture test.gif and puts the picture bit value into a bytea coloumn.
public void addImage() throws SQLException, IOException {
Connection con = openConnection();
File file = new File("test.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = con.prepareStatement("INSERT INTO image VALUES (?, ?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, (int)file.length());
ps.setInt(3,1);
ps.executeUpdate();
fis.close();
}
我的下一个目标是显示保存在的图片数据库以字节为单位。如何做到这一点?
My next goal is to display the picture that is saved in the database in bytes. How can this be done ?
推荐答案
类似于:
// Run a query again the IMAGE table to fetch the image with the given id
public Image readImage(Connection conn, int id) throws SQLException {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("SELECT contents FROM image WHERE id = ?");
pstmt.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
InputStream is = rs.getBinaryStream(1);
return ImageIO.read(is);
} else {
return null;
}
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException ignored) {
}
}
}
}
// Display the given Image on a Swing frame
public void showImage(final Image img) {
JFrame frame = new JFrame("Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(img.getWidth(), img.getHeight());
frame.add(new JPanel() {
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
});
frame.show();
}
可能适合你。
这篇关于从PostgreSQL数据库中显示图像,bytea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文