在不写入磁盘的情况下显示存储为MySQL的BLOB图像

时间:2014-11-24 10:35:25

标签: java mysql swing

我有一个小程序,它将一个图片/图像文件作为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();
}

感谢您的帮助

2 个答案:

答案 0 :(得分:4)

ImageIcon具有构造函数,您可以在其中传递图像字节数组。

 public ImageIcon (byte[] imageData, String description)

所以你可以写这样的东西

ImageIcon ii=new ImageIcon(blob.getBytes(1, (int) blob.length()),"description");

答案 1 :(得分:2)

如图here所示,您可以从InputStream获取Blob并将其传递给ImageIO.read()

Blob blob = resultSet.getBlob(index);
InputStream stream = blob.getBinaryStream(0, blob.length());
BufferedImage image = ImageIO.read(stream);