Retrieve Image JDBC

In the previous code XXXXXX, an image of juggler.gif is inserted in the table marriage. In this program let us read and print. To print, either Frame or Applet window is required.

Here, Retrieve Image JDBC, Frame is used.
import java.sql.*;
import java.io.*;
import java.awt.*;

public class RetrieveImage extends Frame
{
  public static void main(String args[])throws Exception
  {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:snrao","scott","tiger");
    Statement stat= con.createStatement();

    ResultSet rs=stat.executeQuery("select *from marriage");

    rs.next();
    InputStream is = rs.getBinaryStream(1);        // 1 indicates column number in marriage table where image exists

    FileOutputStream fos=new FileOutputStream("Temp.txt"); 

    int k;
    while((k=is.read()) != -1)                      // write the image to file (of Retrieve Image JDBC)
    {
      fos.write(k);
    }

    fos.close();
    rs.close();
    stat.close();
    is.close();
    con.close();

    Frame f = new RetrieveImage();
    f.setSize(300, 350);
    f.setVisible(true);
  }
  public void paint(Graphics g)
  {
    Image img1 = Toolkit.getDefaultToolkit().getImage("Temp.txt");
    g.drawImage(img1, 50, 100, this);                        // write the image to Frame (of Retrieve Image JDBC)
  }
}

Reading the image and printing is a round about process. First image is read from the table and written to a file, Temp.txt. From the file again it is read and displayed on the frame.

g.drawImage(img1, 50, 100, this);

img1: Image to be drawn. The first parameter of drawImage() method is an object Image class.

50, 100: These are x and y coordinates on the frame where image is to be drawn.

this: "this" is an object of ImageObserver which will take care of the image while writing because image will not be written at a time(written step by step).

Leave a Comment

Your email address will not be published.