有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java显示存储在MySQL中的BLOB图像,无需写入磁盘

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

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    如图here所示,您可以从Blob获取一个InputStream并将其传递给^{}

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