1

This code takes picture test.gif and puts the picture bit value into a bytea coloumn.

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();

}

My next goal is to display the picture that is saved in the database in bytes. How can this be done ?

2
  • Display the picture where? webpage, swing app etc? Commented May 21, 2011 at 0:03
  • Display picture in a swing app. The program is actually comand based in Comand Prompt, sow there should be a simpel swing program that shows the picture. Commented May 21, 2011 at 0:20

1 Answer 1

3

Something like:

// 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();
}

might work for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.