Question

I need to show a graphic image from a byte column in database. Below I have the code for a graphic imagem from a physical path.. how can I do it from a byte column?

<h:panelGrid columns="1" style="width:100%" cellpadding="5">  
        <p:graphicImage value="/images/cars/test.jpg"/>                 
</h:panelGrid> 
Was it helpful?

Solution

The <p:graphicImage> supports streaming content. All you need is the following application scoped bean which returns the desired image bytes from the DB based on an unique image identifier as request parameter:

@Named
@ApplicationScoped
public class ImageStreamer {

    @EJB
    private ImageService service;

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

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the image. Return a real StreamedContent with the image bytes.
            String imageId = context.getExternalContext().getRequestParameterMap().get("imageId");
            Image image = imageService.find(Long.valueOf(imageId));
            return new DefaultStreamedContent(new ByteArrayInputStream(image.getBytes()));
        }
    }

}

Here's how you can use it:

<p:graphicImage value="#{imageStreamer.image}">
    <f:param name="id" value="#{someBean.imageId}" />
</p:graphicImage>

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top