Need to use p:graphic image with data from the db?
here is your solution.....
XHTML
<p:graphicImage value="#{imageBean.getImg(148)}" alt="Logo" width="230" height="180"/>
ImageBean (getImg() method only)
NB: inspired by this discussion on LinkedIn
public DefaultStreamedContent getImg(int _id){
try{
img = IOService.getImage(getDs(),_id); //added this line only
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}
else{
if (img == null){
return new DefaultStreamedContent();
}
else{
return new DefaultStreamedContent(new ByteArrayInputStream(img), "image/png");
}
}
}
catch(Exception e){
return new DefaultStreamedContent();
}
}
IOService (heavy lifting done by the getImage() method)
public static byte[] getImage(DataSource d, int _id){
Connection con = null;
byte[] imgBytes = null;
try{
con = d.getConnection();
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("SELECT memberphoto FROM members WHERE memberid = ? limit 1"); //change the SQL here...
ps.setInt(1, _id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
imgBytes = rs.getBytes(1);
// use the data in some way here
}
rs.close();
ps.close();
con.setAutoCommit(true);
}
catch(SQLException ex){
imgBytes = null;
}
catch(ClassCastException exx){
imgBytes = null;
}
finally{
return imgBytes;
}
}
Dont thank me for this......
==============
Footprint:
Primefaces 3.3.1
PostgreSQL 9.0.8
Tomcat7
Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai
ReplyDeleteOnline Java Training Online Java Training | Java J2EE Online Training | JavaEE Training Institute in Chennai