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.
- 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.ObscureRobot– ObscureRobot2011-10-25 23:16:35 +00:00Commented Oct 25, 2011 at 23:16
- It's only a small number of users on the system, so I think it would be appropriate.LOD121– LOD1212011-10-25 23:25:01 +00:00Commented Oct 25, 2011 at 23:25
Add a comment |
1 Answer
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);