从数据库中提取图像(blob)并将其插入Java框架中

从数据库中提取图像(blob)并将其插入Java框架中,java,mysql,swing,Java,Mysql,Swing,我有一个数据库,表“Images”,字段“Img”包含image(类型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.

我有一个数据库,表“Images”,字段“Img”包含image(类型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.
    }
    
这应该行得通

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.
    }