Skip to content

Store and retrieve images

Atul Dwivedi edited this page Oct 22, 2016 · 6 revisions

Store images

  • Images are stored in database as BLOB(i.e. binary large object)
  • Below is the table to create table to save photo with name
CREATE TABLE MYPROFILE 
  ( 
     name  VARCHAR(40), 
     photo BLOB 
  ); 
  • An image can be saved in database using Java FileInputStream
  • PreparedStatement.setBinaryStream accepts InputStream as bytes and submits the same to database
  • Below code snippet displayes how to do it
fin = new FileInputStream("qualifiedPath//photo.jpg");
pstmt.setBinaryStream(index, fin, fin.available());
int i = pstmt.executeUpdate();
  • setBinaryStream method
    • Sets the designated parameter to the given input stream, which will have the specified number of bytes.
    • When a very large binary value is input to a LONGVARBINARY parameter, it may be more practical to send it via a java.io.InputStream object.
    • The data will be read from the stream as needed until end-of-file is reached

Retrieve images

  • ResultSet.getBlob method returns value of the designated column in the current row as a Blob object in the Java programming language
  • Same can be converted in byte array and written as output using FileOutputStream.write
  • See below code snippet
byte barr[] = b.getBytes(1, (int) b.length());
FileOutputStream fout = new FileOutputStream("fileOutputPath//output.jpg");
fout.write(barr);