我有一个数据库,其中有一个表“Images”,其中一个字段“Img”包含图像(BLOB 类型)。
我使用如下查询 SQL 提取图像:
select img from images where id = 1
在java swing项目中如何获取此查询的图像结果?
最佳答案
这应该有效
Blob blob = rs.getBlob("img");
int blobLength = (int) blob.length();
byte[] bytes = blob.getBytes(1, blobLength);
blob.free();
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
您可以选择如何将其添加到框架中。您可以将其添加到 JLabel
中,也可以将其绘制在 JPanel
上。仅取决于您的要求和/或偏好。
使用
JLabel
ImageIcon icon = new ImageIcon(bytes); // you can read straight from byte array JLabel label = new JLabel(icon); frame.add(label);
在
JPanel
上绘画@Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // img is the BufferedImage in the first code. }
关于java - 从数据库中提取图像(blob)并将其插入到框架中 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887882/