Saturday, July 6, 2013

Retrieving image from database made easy by p:graphicImage

In a Java web application, if we are going to display image(s) from database (stored in blob).
Normally it is going through an Image Servlet to convert the byte[] to an image file before render it in the screen.

With PrimeFaces's <p:graphicImage />, no additional Image Servlet is required.
What we need here is just to convert the byte[] to StreamedContent.

Converting byte[] to StreamedContent

public StreamedContent getImage() {
    byte[] imageInByteArray = IMAGE_IN_BYTE_ARRAY_FROM_DB;
    return new DefaultStreamedContent(new ByteArrayInputStream(imageInByteArray), "image/png");

Displaying StreamedContent in p:graphicImage

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




Related Posts Plugin for WordPress, Blogger...