2

How do you save and load an image from a database and display it in Java? I can get the file location, but I am unsure as to how to save it as a blob in the database or display the image in a swing window. I am using a PreparedStatement to get information in and out of the database.

2
  • Are you sure storing an image in your MySQL database is a good idea? Images tend to be large, and SQL databases aren't a great way to store unstructured blobs of data. Commented Oct 25, 2011 at 23:16
  • It's only a small number of users on the system, so I think it would be appropriate. Commented Oct 25, 2011 at 23:25

1 Answer 1

3

See this MySQL Java tutorial for examples under the sections Writing images and Reading images. In outline,

// writing String sql = "INSERT INTO Images(Data) VALUES(?)"; PreparedStatement pst = con.prepareStatement(sql); FileInputStream fin = new FileInputStream(myFile); pst.setBinaryStream(1, fin, (int) myFile.length()); pst.executeUpdate(); //reading String query = "SELECT Data FROM Images LIMIT 1"; PreparedStatement pst = con.prepareStatement(query); ResultSet result = pst.executeQuery(); result.next(); String fileName = "src/main/resources/tree.png"; FileOutputStream fos = new FileOutputStream(fileName); Blob blob = result.getBlob("Data"); int len = (int) blob.length(); byte[] buf = blob.getBytes(1, len); fos.write(buf, 0, len); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.