Creating dynamic image streaming programmatically

The graphicImage component can also render an image that is created programmatically in the server-side backing bean.

How to do it…

The following is an example that renders a PrimeFaces logo, which is read with the resource streaming mechanism:

<p:graphicImage value="#{dynaImageBean.graphicText}" />

public StreamedContent getGraphicText() throws IOException {
  InputStream stream =this.getClass()
    .getResourceAsStream("/chapter7/primefaces.jpg");
  return new DefaultStreamedContent(stream);
}

How it works...

As seen, the getGraphicText() method returns an instance of StreamedContent. PrimeFaces also provides a default implementation for the stream content, which is org. primefaces.model.DefaultStreamedContent. The backing bean containing the graphicText getter method should be defined in the session scope. The reason behind this is that the image will be fetched in a separate request from the rest of the page content, and in order to retrieve the logo image, the content should be stored in the session context.

PrimeFaces Cookbook Showcase application

This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on every Servlet 3.x compatible application server, such as JBoss WildFly or Apache TomEE.

The showcase for the recipe is available under http://localhost:8080/pf-cookbook/views/chapter7/dynaImage.jsf.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.190.175