Saturday 1 February 2014

Display Multiple Images: Struts 2 Iterator

This post addresses below topics
1. Display Multiple Images using Struts 2 iterator
2. Struts Hibernate Image Gallery
3. Storing Image file into MySQL database through Struts Action and Hibernate.
4. Display dynamic BLOB / byte array image on JSP using Struts 2.
5. Convert Byte Array to Image
6. Display image along with image content.
7. Create a dynamic image gallery.

This tutorial comprises of 4 Steps
1. Read an image and store into database
2. Get image from database using hibernate
3. Display image on JSP dynamically
4. Construct an Image gallery following above steps

1. Read an image and store into database

Below is the code example from my project where I am reading image from local directory file, then converting the image into byte array and then storing into MySQL database.

In database you need to create a table and add a column with type BLOB or LONG BLOB to store the image byte array.
 public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://IP-AddrOrHostName:Port/database-name", "user-id", "password");
    String INSERT_PICTURE = "insert into image_table(image_id, image_src, image_title) values (?, ?, ?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("C:/Ankit/workspace/image.jpg");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "1"); //This is image ID
      ps.setBinaryStream(2, fis, (int) file.length());
      //Or you can also use this:
      //ps.setBlob(2, fis, (int) file.length());
      ps.setString(3, "Ready for the Event?"); //This is image Title
      ps.executeUpdate();
      conn.commit();
    }
    catch(Exception ex){
     ex.printStackTrace();
    }
    finally {ps.close();
      fis.close();
    }
  }

2. Get image from database using hibernate
 If you are working with hibernate POJOs, make sure you use a byte array field which would map to the blob column we created in step 1.
Otherwise if you are simply working with JDBC/ODBC take out the result set output into a byte array field.
Would post code shortly :)