Show an InputStream as dynamic image in JSF

不羁的心 提交于 2019-11-29 12:19:50
BalusC

OmniFaces does not offer any utility for this — yet.

If the image files are located on the disk file system, then you need to create a virtual context in the servletcontainer configuration so that they can be accessed by a normal URL. See also Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag.

If the image files are stored in the DB, then you need to create a simple servlet which just writes the InputStream of the image from the DB to the OutputStream of the HTTP response. See also How to retrieve and display images from a database in a JSP page? (note that this doesn't require JSP/HTML, you can as good just use <h:graphicImage> as it merely generates a HTML <img> element).

There's the PrimeFaces <p:graphicImage>, but this is a bit unintuitive to implement. See also Display dynamic image from database with p:graphicImage and StreamedContent.


Update: since OmniFaces 2.0 (for JSF 2.2) there's a <o:graphicImage> component which supports among others directly referencing a byte[] or InputStream property in an @ApplicationScoped managed bean in an intuitive way like below:

<o:graphicImage value="#{imageStreamer.getById(bean.imageId)}" />
@Named
@ApplicationScoped
public class ImageStreamer {

    @Inject
    private ImageService service;

    public InputStream getById(Long id) { // byte[] is also supported.
        return service.getContent(id);
    }

}

In contrary to PrimeFaces <p:graphicImage>, no <f:param> is needed and the EL method arguments are evaluated during render response phase, but the EL method itself is only invoked when the browser actually requests the image. See also the showcase and the blog on the subject.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!