1

I have a Image loaded from a database as a byte[]. Does anyone have a Bean example of how to turn it into a StreamedContent object and use it in the <p:graphicImage value="#{bean.image}"/>?

Thanks.

Eduardo
  • 148
  • 2
  • 14

2 Answers2

2
@Named
public class ImageBean {
    private StreamedContent image;
    @PostConstruct
    public void init() {
        image = new DefaultStreamedContent(new ByteArrayInputStream(byteArray)); // your byte array
    } 
    // setter and getter for image omitted
}

Then you call #{imageBean.image} in your xhtml page on a p:graphicImage element

Meme Composer
  • 5,895
  • 4
  • 18
  • 33
  • Thanks for answering in a clear and objective way. I had a feeling that I'd done this before, apparently not. – Eduardo Dec 05 '16 at 10:42
0

First of all, you should read this great answer for an example on how a bean for serving StreamedContent should look like.

For your special origin there also exists a ByteArrayContent which is furthermore serializable.

To use

<p:graphicImage value="#{bean.image}" />

your bean will have to look something like this:

@Named
@ApplicationScoped
public class Bean {

  private byte[] imageLoadedFromDatabase;

  // code to set (or load) image from database
  ... 

  public StreamedContent getImage() {
    if (FacesContext.getCurrentInstance().getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
        return new DefaultStreamedContent();
    } else {
        return new ByteArrayContent(imageLoadedFromDatabase);
    }
  }
}
Community
  • 1
  • 1
irieill
  • 908
  • 6
  • 21
  • Thanks for answering. I read that answer you suggest before and unfortunately it did not work for me (actually the omnifaces bit worked, but I got some other problems with it afterwards, so I'm back with primefaces). – Eduardo Dec 05 '16 at 10:46