Java Retrieve image

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Example to retrieve image from Oracle database

By the help of PreparedStatement we can retrieve and store the image in the database.

The getBlob() method of PreparedStatement is used to get Binary information, it returns the instance of Blob. After calling the getBytes() method on the blob object, we can get the array of binary information that can be written into the image file.

Signature of getBlob() method of PreparedStatement

  1. public Blob getBlob()throws SQLException  

Signature of getBytes() method of Blob interface

  1. public  byte[] getBytes(long pos, int length)throws SQLException  

We are assuming that image is stored in the imgtable.

  1. CREATE TABLE  "IMGTABLE"   

  2.    (    "NAME" VARCHAR2(4000),   

  3.     "PHOTO" BLOB  

  4.    )  

  5. /  

Now let's write the code to retrieve the image from the database and write it into the directory so that it can be displayed.

In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by the img tag.

  1. import java.sql.*;  
  2. import java.io.*;  
  3. public class RetrieveImage {  
  4. public static void main(String[] args) {  
  5. try{  
  6. Class.forName("oracle.jdbc.driver.OracleDriver");  
  7. Connection con=DriverManager.getConnection(  
  8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  9.       
  10. PreparedStatement ps=con.prepareStatement("select * from imgtable");  
  11. ResultSet rs=ps.executeQuery();  
  12. if(rs.next()){//now on 1st row  
  13.               
  14. Blob b=rs.getBlob(2);//2 means 2nd column data  
  15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image  
  16.               
  17. FileOutputStream fout=new FileOutputStream("d:\sonoo.jpg");  
  18. fout.write(barr);  
  19.               
  20. fout.close();  
  21. }//end of if  
  22. System.out.println("ok");  
  23.               
  24. con.close();  
  25. }catch (Exception e) {e.printStackTrace();  }  
  26. }  
  27. }  

Now if you see the d drive, sonoo.jpg image is created.