display byte array as image from database using richfaces and JPA
rlemerson Jun 29, 2012 10:40 AMHi,
I'm new to Richfaces and JPA. I'm currently working on an image cover flow where all images will be coming from a mysql database where they are stored as mediumblob. I was curious if someone can easily display a persisted byte array retrieved from the database as an image using Richfaces and JPA? I've been spinning my wheels trying to come up with a workable solution without having to do this an archaic way.
Currently, I have a persistent "Screenshot" class:
@Entity @XmlRootElement @Table(name="Jun2012", uniqueConstraints = @UniqueConstraint(columnNames = "id")) public class Screenshot implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; private String user; private Timestamp time; private String mode; @Lob private byte[] png; **** Getters/Setters,,,,,,, **** }
Also, in another class I'm producing a list of screenshots:
@RequestScoped public class ScreenshotListProducer { @Inject private EntityManager em; private List<Screenshot> screenshots; @Produces @Named public List<Screenshot> getScreenshots() { return screenshots; } public void onScreenshotListChanged(@Observes(notifyObserver = Reception.IF_EXISTS) final Screenshot screenshot) throws FileNotFoundException { retrieveAllScreenshotsOrderedByTime(); } @PostConstruct public void retrieveAllScreenshotsOrderedByTime() throws FileNotFoundException { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Screenshot> criteria = cb.createQuery(Screenshot.class); Root<Screenshot> screenshot = criteria.from(Screenshot.class); criteria.select(screenshot).orderBy(cb.asc(screenshot.get("time"))); screenshots = em.createQuery(criteria).getResultList(); } }
My current usage in my xhtml is as follows:
........ ........ <!-- Load .png images from the database --> <div class="ContentFlow"> <div class="loadIndicator"><div class="indicator"></div></div> <div class="flow"> <ui:repeat var="img" value="#{screenshots}"> <img class="item" src="#{img.png}" title="#{img.mode}"/> </ui:repeat> </div> <div class="globalCaption"></div> <div class="scrollbar"><div class="slider"><div class="position"></div></div></div> </div> .......... ..........
My image cover flow successfully shows my mode within title, but obviously doesn't show my png image since it hasn't been converted. Is there an easy way to convert the byte array to an image in this context?
Any help is very much appreciated.