【问题标题】:Displaying image from PostgreSQL database, bytea显示来自 PostgreSQL 数据库的图像,bytea
【发布时间】:2011-05-20 23:25:40
【问题描述】:

此代码获取图片 test.gif 并将图片位值放入 bytea 列中。

public void addImage() throws SQLException, IOException {
    Connection con = openConnection();

    File file = new File("test.gif");
    FileInputStream fis = new FileInputStream(file);
    PreparedStatement ps = con.prepareStatement("INSERT INTO image VALUES (?, ?, ?)");
    ps.setString(1, file.getName());
    ps.setBinaryStream(2, fis, (int)file.length());
    ps.setInt(3,1);
    ps.executeUpdate();
    fis.close();

}

我的下一个目标是以字节为单位显示保存在数据库中的图片。这是怎么做到的?

【问题讨论】:

  • 在哪里显示图片?网页、swing 应用等?
  • 在摇摆应用中显示图片。该程序实际上是基于Comand Prompt中的comand,所以应该有一个简单的swing程序显示图片。

标签: java image postgresql


【解决方案1】:

类似:

// Run a query again the IMAGE table to fetch the image with the given id
public Image readImage(Connection conn, int id) throws SQLException {
  PreparedStatement pstmt = null;
  try {
    pstmt = conn.prepareStatement("SELECT contents FROM image WHERE id = ?");
    pstmt.setInt(1, id); 
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
      InputStream is = rs.getBinaryStream(1);
      return ImageIO.read(is);
    } else {
      return null;
    }
  } finally {
    if (pstmt != null) {
      try {
        pstmt.close();
      } catch (SQLException ignored) {
      }
    }
  }
}

// Display the given Image on a Swing frame
public void showImage(final Image img) {
  JFrame frame = new JFrame("Image");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(img.getWidth(), img.getHeight());
  frame.add(new JPanel() {
    public void paint(Graphics g) {
      g.drawImage(img, 0, 0, null);
    }
  });
  frame.show();
}

可能对你有用。

【讨论】:

    猜你喜欢
    • 2014-04-08
    • 1970-01-01
    • 2013-05-19
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2016-11-23
    相关资源
    最近更新 更多