从字节列DB获取p:graphicImage

时间:2013-11-01 18:03:36

标签: database jsf jsf-2 primefaces graphicimage

我需要显示数据库中字节列的图形图像。下面我从物理路径获取图形图像的代码..如何从字节列中进行操作?

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

1 个答案:

答案 0 :(得分:1)

<p:graphicImage>支持流媒体内容。您所需要的只是以下应用程序作用域bean,它根据唯一的图像标识符作为请求参数从DB返回所需的图像字节:

@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()));
        }
    }

}

以下是如何使用它:

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

另见: