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


Apache Tomcat V7.0


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"
<html xmlns="http://www.w3.org/1999/xhtml"
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<title>JSF PrimeFaces graphicImage Example</title>
	<h3>JSF PrimeFaces 5.2 graphicImage Example</h3>
	<h:form id="imageForm" prependId="false">

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

		<p:separator />

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

		<p:separator />

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



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")
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()
			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,
			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),




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 {
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/test", "root", "*****");
		} catch (Exception e) {

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

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


		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


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

graphicImage example

Reference: GraphicImage

Leave a Reply