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

just chill cbd oil how long does cbd oil take to work puur cbd oil cbd 30 mg gummies mr lees cbd cbd news cbd for period cramps will cbd affect a drug test e liquid cbd cbd trials cbd christian bookstore cbd oil brain cbd oil lowers blood pressure cbd american shaman products can cbd help with allergies cbd in alaska kushy punch cbd gummies how long do cbd edibles last making cbd gummies cbd wellness artistic organics cbd store dothan al is cbd in hemp terpenes cbd oil review cbd inhaler to quit smoking cbd in mn cbd oil effects on artery blockage cbd payment processors cbd oil woodstock ga soothe cbd oil cbd cramps native brand cbd oil plantacea cbd chemical cbd cbd for healing cbd oil for pregnancy can you give cbd oil to your pets cbd oil buying prestige cbd oil how does cbd oil taste best cbd oil for bipolar back pain cbd oil quicksilver cbd reviews cbd oil bad for you cbd oil hoax cbd oil near 48178 does cbd oil come up on drug test waterloo iowa cbd oil hemp gummies vs cbd gummies cannabis oil treatment for autism extract labs cbd

top 10 penis enlargement fda erection pills male enhancement surgery near me male enhancement best male enhancer sperm production supplement over the counter drug for anxiety prescription male enhancement birth control pills online kamasutra male enhancement pills ed pills used by michael douglas male enhancement pills free male enhancement facts top 10 male enhancement pill sex enhancement products gaines male enhancement sex under the influence of drugs hcg penis enlargement best male enhancement pills in ghana penis enlargement ecard spikenard for penis enlargement drug orgasm penis enlargement exercises free liquid iron supplement walmart nitrix 20 penis enlargement men with blue pills male libido booster pills long sta over thevcounter ed pills libidol tablet best gnc supplements for ed pills to decrease libido extenze the male enhancement with pill enhancerx promotional code rhino products male enhancement max performer tablets jonah hill male enhancement pills natural dick pills superman workout pill sex pills as mentioned on doctor oz show horsetail penis enlargement male enhancement z ebay virility max sex pills troya pills small purple pill cooper hefners son new sex enhancement pill 2020 top tablets images of male nipple enhancement which male enhancement pills really work wal mart male enhancement benefits of male sexual enhancement pills male enhancement pills at costco

does any weight loss supplement work diet chart for weight loss for female pdf fastest weight loss without pills weight loss hypothyroidism diet fiber pills weight loss dr oz the most effective keto pills for weight loss diet dash weight loss best supplements for weight loss for men diet meal plans for weight loss weight loss benefits of apple cider vinegar pills weight loss drug online what is thermogenic weight loss pills what supplements are good for weight loss paleo diet loss weight shark tank keto diet pills episode you tube hemp hearts weight loss diet vegetables diet to lose weight weight loss on all liquid diet realistic diet plan to lose weight pills that really work for weight loss hypothyroid diet lose weight paleo diet weight loss stories easy diet tips to lose weight fast weight loss diet plan in india weight training to lose weight diet plan diet meal plans for weight loss global weight loss supplements 50 protein diet weight loss weight loss pill from shark tank 7 day diet to lose weight fast diet for cyclists to loss weight best diet to lose weight fast new weight loss drug approved by the fda keto diet grilled chicken recipes pills for weight loss force factor dietary supplement weight loss which illegal drug causes weight loss diet food programs to lose weight reviews birth control pills for weight loss pcos weight loss pills close to prescription red wine diet for weight loss low carb diet how long before weight loss keto diet and intermittent fasting weight loss popular diet plan for weight loss how much weight loss can you lose keto diet best lose weight tablets take caffeine pills everyday lose weight why do so many weight loss diets fail to work weight loss pill ibm what is 100 bhb in keto diet pills