p:graphicImage tag in JSF Primefaces. Example code for displaying dynamic images.

In this tutorial, let us see that how to render images in browser using Primefaces <p:graphicImage> tag. This tag allows you to render images  of any static image file or dynamically generated images or images stored in a database. The <p:graphicImage> tag of Primefaces is converted to html <img> tag when the user requests any jsf page having this tag.

Now let us see how this tag is used to render images.

1. Rendering images of any static image file

For rendering static image file, you need to mention the path of the image file in the URL attribute.

<p:graphicImage url=”/resources/images/test.jpg” />

2. Rendering dynamically generated images or images stored in a database:

<p:graphicImage> is capable of rendering binary data  (streamed content). The below statement renders binary data as image in the browser.

<p:graphicImage value=”#{imageBean.image}”/>
<p:graphicImage value=”#{imageBean.imageFromDB}”/>

where image and imageFromDB are properties of managed bean that return streamed content.

Now Let us see an example   for rendering the image generated at run time and the image stored in a database.

Technology used in the project:

JSF 2.2

Primefaces 5.2

Eclipse

Apache Tomcat V7.0

MySQL

Java 1.7

I) Creating  a JSF page  rendering images.

JSF Page (GraphicImageExample.xhtml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<title>JSF PrimeFaces graphicImage Example</title>
</h:head>
<h:body>
	<h3>JSF PrimeFaces 5.2 graphicImage Example</h3>
	<h:form id="imageForm" prependId="false">

		<p:column>
			<div style="vertical-align: text-top;">1.</div>
		</p:column>
		<p:column>
			<p:graphicImage url="/images/test.jpg" />
		</p:column>

		<p:separator />

		<p:column>
			<div style="vertical-align: text-top;">2.</div>
		</p:column>
		<p:column>
			<p:graphicImage value="#{imageBean.image}">
			</p:graphicImage>
		</p:column>

		<p:separator />

		<p:column>
			<div style="vertical-align: text-top;">3.</div>
		</p:column>
		<p:column>
			<p:graphicImage value="#{imageBean.imageFromDB}">
			</p:graphicImage>
		</p:column>

	</h:form>

</h:body>
</html>

The above JSF page renders 3 images using <p:graphicImage> tag.
1. image of a static image file.
2. image generated at run time
3. image stored in a database
Now let us write managed bean code associated with the components of the above JSF page

II) Write Managed Bean code for the JSF page

Managed Bean (GraphicsImage.java):

Manage Bean has two getter methods.

1. getImage() – The original image is read from a static file, scaled at run time and returned as streamd content.

2. getImageFromDB() – The image is read from the DB as bytes and returned as stream content.
The complete code of managed bean is given below.

package net.javaonline.jsf.primefaces.multiplefileupload.controller;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.imageio.ImageIO;

import net.javaonline.jsf.primefaces.multiplefileupload.dao.ProductImageDAO;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean(name = "imageBean")
@RequestScoped
public class GraphicImage implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public StreamedContent getImage() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			BufferedImage img = ImageIO.read(context.getExternalContext()
					.getResourceAsStream("/images/p.jpg"));
			int w = img.getWidth(null);
			int h = img.getHeight(null);

			// image is scaled two times at run time
			int scale = 2;

			BufferedImage bi = new BufferedImage(w * scale, h * scale,
					BufferedImage.TYPE_INT_ARGB);
			Graphics g = bi.getGraphics();

			g.drawImage(img, 10, 10, w * scale, h * scale, null);

			ImageIO.write(bi, "png", bos);

			return new DefaultStreamedContent(new ByteArrayInputStream(
					bos.toByteArray()), "image/png");

		}
	}

	public StreamedContent getImageFromDB() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {

			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			// Reading image from database assuming that product image (bytes)
			// of product id I1 which is already stored in the database.

			byte[] image = null;
			try {
				image = new ProductImageDAO().getProductImage("I1");
			} catch (SQLException e) { // TODO Auto-generated catch block
										// e.printStackTrace();
			}

			return new DefaultStreamedContent(new ByteArrayInputStream(image),
					"image/png");

		}
	}

}

 

III) Write DAO code for accessing database and retrieving binary data (image) using product code.

Database Access code (ProductImageDAO.java)
package net.javaonline.jsf.primefaces.multiplefileupload.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProductImageDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public byte[] getProductImage(String productId) throws IOException,
			SQLException {
		Connection con = null;
		PreparedStatement stmt = null;
		byte[] productImage = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/test", "root", "*****");
		} catch (Exception e) {
			System.out.println(e);
			System.exit(0);
		}

		stmt = con.prepareStatement("select * from product where productId=?");
		stmt.setString(1, productId);
		ResultSet rs = stmt.executeQuery();

		while (rs.next()) {
			productImage = rs.getBytes("productImage");
		}

		rs.close();
		con.close();

		return productImage;
	}

}

 

Prerequisites for this project:
  1. Place an image file (test.jpg) under WebContent/images folder
  2. Create a table (Product) with the following fields in MySQL

+————–+————–+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+————–+————–+——+—–+———+——-+
| productId | varchar(10) | NO | PRI | NULL | |
| productName | varchar(100) | NO | | NULL | |
| productImage | mediumblob | YES | | NULL | |
+————–+————–+——+—–+———+——-+

Add product details with Image.

For example,

productId : I1

prodcutName : Samsung LED TV

productImage : binary data  to be uploaded in blob field

For uploading binary file and storing in MySQL table, you can visit my earlier tutorial Storing PDF file in MySQL table

 

Run the application by calling the URL

localhost:8080/JSFExamples/faces/GraphicImageExample.xhtml

Now 3 images are displayed.  Second one is the scaled image of first one.

graphicImage example

Reference: GraphicImage

Leave a Reply