Show an InputStream as dynamic image in JSF

前端 未结 1 1387
小蘑菇
小蘑菇 2020-12-20 03:19

How can we embed and show an InputStream as dynamic image in JSF 2.0 with OmniFaces?

相关标签:
1条回答
  • 2020-12-20 04:09

    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.

    0 讨论(0)
提交回复
热议问题