Links

   Quran Explorer - Interactive Audio Recitations & Translations

Tuesday, January 7, 2014

Primefaces GraphicImage from the datatabase

Hello

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

1 comment:

Feel free to leave a comment