显示来自PostgreSQL数据库的图像bytea
发布于 2021-01-30 16:42:41
此代码将图片test.gif放入图片位值中。
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();
}
我的下一个目标是显示以字节为单位保存在数据库中的图片。如何才能做到这一点 ?
关注者
0
被浏览
95
1 个回答
-
就像是:
// 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(); }
可能为您工作。