通过postgres中的bytea数据类型通过SetIcon更新JLabel

时间:2015-09-17 05:31:19

标签: java postgresql

我正在从Wolfram | Alpha检索gif图像。为了最大限度地减少查询,我想存储这些图像,并且只在更改数据时查询W | A,所以我将图像存储为我的postgres数据库中的bytea数据类型。 "保存"部分似乎有效,因为有数据。 System.out.println(rs.getString("fnPlotImg"))会产生这样的结果:\x4275666665726564496d6167654035356437373834323a2074797065203d203120446972656374436f6c6f724d6f64656c3a20726d61736b3d66663030303020676d61736b3d6666303020626d61736b3d666620616d61736b3d3020496e7465676572496e7465726c65617665645261737465723a207769647468203d2032303020686569676874203d20313335202342616e6473203d203320784f6666203d203020794f6666203d203020646174614f66667365745b305d2030

我已经能够使用这段代码成功更新W | A中的图像:

String path = ((WAImage) element).getURL();
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
picLabel.setIcon(new ImageIcon(image));

我想用数据库中的图像更新我的应用程序并尝试使用此代码:

byte[] ba = rs.getBytes("fnPlotImg");
try{
    picLabel.setIcon(new ImageIcon(ba));
} catch (NullPointerException e) {
    e.printStackTrace();
}

我的理由是bytea是一个字节数组,getBytes()应该检索一个字节数组,而ImageIcon()应该处理一个字节数组。但是,如果我不构建一个空指针例外,它出错了。我认为这是因为我没有正确地将图像保存到DB或者我没有正确地检索它。

欢迎所有的想法,我感到疲惫,所以我早上会以新的眼光检查。

1 个答案:

答案 0 :(得分:2)

我没有安装PostgreSQL,但我认为您应该编写/阅读图像格式,而不是BufferedImage数据。

例如,写作可能看起来像......

Connection con = ...;
BufferedImage img = ...;
try (PreparedStatement stmt = con.prepareStatement("insert into tableofimages (image) values (?)")) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(img, "png", baos);
        try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
            stmt.setBinaryStream(1, bais);
            int rows = stmt.executeUpdate();
            System.out.println(rows + " rows updated");
        }
    }
} catch (SQLException | IOException exp) {
    exp.printStackTrace();
}

阅读可能看起来像......

Connection con = ...;
try (PreparedStatement stmt = con.prepareStatement("select image from tableofimages")) {
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            try (InputStream is = rs.getBinaryStream(1)) {
                BufferedImage img = ImageIO.read(is);
            }
        }
    }
} catch (SQLException | IOException exp) {
    exp.printStackTrace();
}