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}" />


Done!!

3 comments:

  1. I am fairly new to programming. I often find myself struggling with tasks like this. Your step-by-step guide made the process manageable. I'm sure it will also be a valuable resource for many other beginners. Cheap Dissertation Writing Service

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...