user3780616
user3780616

Reputation: 1273

JSF updating h:graphicImage

I'm using poll from primefaces to update an image every n seconds. I'm flipping between two images right now just to make sure it's working. Now what I'm trying to do is display images that aren't stored on the server. I wrote a class that snaps a photo every n seconds. I don't want to save it to disk to reduce IO. So I'd like to do something like the following flow

@ManagedBean
@ViewScoped
public class myClass implements Serializable {
  public Object getImage() {
    Object newImage = MyClass.takePhoto();
    return newImage;
  }

  public void increment() {
  }
}

XHTML:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <h:head></h:head>
    <h:body>
      <h:form>
        <h:graphicImage value="#{myClass.image}" id="img" cache="false"/>
        <p:poll interval="1" listener="#{myClass.increment}" update="img" />
      </h:form>
    </h:body>
</h:html>

So my question is, is it possible to return an Image object to h:graphicImage in a similar way to the pseudo-code above?

Upvotes: 1

Views: 2222

Answers (1)

starf
starf

Reputation: 1093

Yes, try using the Primefaces StreamedContent class to provide a stream to graphicImage, rather than an object.

Something like:

public StreamedContent getImageStream() {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(myBufferedImage, "png", os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());
    return new DefaultStreamedContent(is, "image/png");

}

Then in your JSF page:

<p:graphicImage value="#{myController.imageStream}" cache="false"/>

Note that this uses p:graphicImage, rather than h:graphicImage.

Upvotes: 3

Related Questions