Thursday, 1 August 2013

How to save an Image and read back from database in Java?

Example to insert an image into the database and read from database




The setBinaryStream() method is used to set Binary information into the parameterIndex. This method is available in the PreparedStatement interface.

  • Public void setBinaryStream(int paramIndex, InputStream in) throws SQLException
  • Public void setBinaryStream(int paramIndex, InputStream in, int length) throws SQLException

For storing an image into the database we can use BLOB datatype in the table.We can create a table using below CREATE TABLE command in MYSQL database.

Table Structure for MySql Database:-

CREATE TABLE persist_java_objects (
object_id int(14) NOT NULL auto_increment,
object_name varchar(30) default NULL,
java_object blob,
PRIMARY KEY  (object_id)
)


System Requirements:-

jdk1.5 and above(I am using jdk1.7)
Eclipse Editor or other(I am using Eclipse Helios).

Required Jars:-

mysql-connector-java-5.0.4-bin.jar

Sample Example to save an image into database and read back from database and open with default image viewer or browser:-



packagecom.gaurav.persistjavaobjects;

importjava.awt.Desktop;
import java.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStream;
import java.sql.Blob;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;

public classSaveImage2Database {

            privatestatic Connection getConnection() throws Exception {
                        String driver = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://localhost:3306/test";
                        String username = "root";
                        String password = "root";
                        Class.forName(driver);
                        Connection con = DriverManager.getConnection(url, username, password);
                        returncon;
            }

            /** This method will help to save an image object into database */
            privatestatic long saveImageFile(Connection con, String fileName) {

                        PreparedStatement preparedStatement = null;
                        String SQLQUERY_TO_SAVE_JAVAOBJECT = "INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?)";
                        intpersistObjectID = -1;
                        try{

                                    File file = new File(fileName);
                                    FileInputStream fileInputStream = new FileInputStream(file);

                                    // This will help to request for returning the generated key
                                    preparedStatement = con.prepareStatement(
                                                            SQLQUERY_TO_SAVE_JAVAOBJECT,
                                                            PreparedStatement.RETURN_GENERATED_KEYS);

                                    preparedStatement.setString(1, fileName.getClass().getName());
                                    preparedStatement.setBinaryStream(2, fileInputStream,
                                                            (int) file.length());
                                    preparedStatement.executeUpdate();

                                    System.out
                                                            .println("Query - "
                                                                                    + SQLQUERY_TO_SAVE_JAVAOBJECT
                                                                                    + " is successfully executed for Java object serialization ");

                                    // Trying to get the Generated Key
                                    ResultSet rs = preparedStatement.getGeneratedKeys();

                                    if(rs.next()) {
                                                persistObjectID = rs.getInt(1);
                                                System.out
                                                                        .println("Object ID while saving the binary object is->"
                                                                                                + persistObjectID);
                                    }

                                    preparedStatement.close();
                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        returnpersistObjectID;
            }

            /** This method will help to read an image object from database */
            privatestatic void getBlob(Connection con, long objectId) {
                        String SQLQUERY_TO_READ_JAVAOBJECT= "SELECT java_object FROM persist_java_objects WHERE object_id = ?;";
                        PreparedStatement pstmt = null;
                        ResultSet resultSet = null;
                        Blob blobData = null;

                        try{
                                    pstmt = con.prepareStatement(SQLQUERY_TO_READ_JAVAOBJECT);
                                    System.out.println("Object Id is:->" + objectId);
                                    // Setting the same object id which we got during image object save
                                    pstmt.setLong(1, objectId);

                                    resultSet = pstmt.executeQuery();

                                    while(resultSet.next()) {
                                                blobData = resultSet.getBlob("java_object");

                                                InputStream inputStream = blobData.getBinaryStream();

                                                intsize = inputStream.available();

                                                FileOutputStream out = new FileOutputStream(
                                                                        "c://Image//Thank.gif");

                                                byteb[] = new byte[size];
                                                inputStream.read(b);
                                                out.write(b);
                                                out.close();
                                    }

                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }

            }

            publicstatic void main(String args[]) throws Exception {
                        Connection connection = null;

                        try{
                                    connection = getConnection();
                                    String fileName = "G://GIF//ThankYou.gif";
                                    longpersistObjectID = saveImageFile(connection, fileName);
                                    System.out.println("Image is saved sucessfully");

                                    // Calling the method to read the image from database.
                                    getBlob(connection, persistObjectID);

                                    System.out
                                                            .println("Successfully retrieved java Object from Database");

                                    String fileNameAfterRead = "c://Image//Thank.gif";
                                    /**

                                     * This piece of code will help to open the image file in default

                                     * image viewer.

                                     */
                                   File fileName2Open = new File(fileNameAfterRead);
                                   Desktop desktop = Desktop.getDesktop();
                                   desktop.open(fileName2Open);
                                   System.out.println("File Opened successfully at the first time.");

                                    /**

                                     * This piece of code will help to open the image file in default

                                     * browser.

                                     */
                                    String[] executionCommands = { "cmd.exe", "/c", "start",
                    "\"ThankYouImage\"", "\"" + fileNameAfterRead + "\"" };
                                    Process process = Runtime.getRuntime().exec(executionCommands);
                                    process.waitFor();
                                    System.out.println("File Opened successfully at the second time.");

                        } catch (Exception e) {
                                    e.printStackTrace();
                        } finally {
                                    connection.close();
                        }
            }
}

Result:-

Query - INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?) is successfully executed for Java object serialization
Object ID while saving the binary object is->6
Image is saved sucessfully
Object Id is:->6
Successfully retrieved java Object from Database
File Opened successfully at the first time.
File Opened successfully at the second time.

Table Status after image insertion:-
 

No comments:

Post a Comment