0

I want to display a dynamic photo with I'm storing the content of the image as a blob in the database , the content type in the photo entity is a byte array (byte[]) . I tried two diffrent ways but both was useless.

1)

 public StreamedContent getImage() throws IOException {
  byte[] img=photo.getContent();
 InputStream in = new ByteArrayInputStream(img);
 StreamedContent  image = new DefaultStreamedContent(in,"image/jpeg");
  return image;
}

2)

public StreamedContent getImage() throws IOException {
  byte[] img=photo.getContent();
 InputStream in = new ByteArrayInputStream(img);
 BufferedImage bufferedImg = ImageIO.read(in);
 ByteArrayOutputStream os = new ByteArrayOutputStream();
 ImageIO.write(bufferedImg, "jpeg", os);

 StreamedContent   image = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()),"image/jpeg");

  return image;
}

and in the view page :

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

So could someone help me to make it work !!

siebz0r
  • 18,867
  • 14
  • 64
  • 107
MarwaInsat
  • 293
  • 1
  • 4
  • 17

1 Answers1

2

You first must retrieve the blob from the database.

public StreamedContent getImage() throws SQLException {
    Blob imgBlob;
    try
    {
     //Select the blob from your database here. Use a PreparedStatement (I'll call it stmt here) for this.
     ...
     ResultSet res = stmt.executeQuery();
     res.next();
     imgBlob = res.getBlob("columnName");
    }
    catch(SQLException e){ throw e; }
    byte[] img=imgBlob.getBytes(1, imgBlob.length()); //Get the blob as a byte array
    InputStream in = new ByteArrayInputStream(img);
    StreamedContent  image = new DefaultStreamedContent(in,"image/jpeg");
    return image;
}

More info about the Blob class.

Carlos Vergara
  • 3,592
  • 4
  • 31
  • 56
  • ' Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sensordb","root","root"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT content FROM photo where idPhoto="+id); rs.next(); InputStream binaryStream = rs.getBinaryStream("content"); ' – MarwaInsat Oct 08 '12 at 20:03
  • That's the problem, you're trying with `getBinaryStream`. Try with `getBlob` instead. – Carlos Vergara Oct 08 '12 at 20:09
  • I tried with getBlob also and it didnt work , i tried all possibilies but i's useless :( – MarwaInsat Oct 08 '12 at 20:48
  • i dont get errors but the photo is not displayed (an empty small icon is only displayed instead of the photo) – MarwaInsat Oct 09 '12 at 09:53
  • Do the query manually in mySQL and see what results you're getting. Also, is `id` setted correctly? – Carlos Vergara Oct 09 '12 at 14:14
  • yes i already did it and the query is returning the content of the image correctly so i have problem in the display :( – MarwaInsat Oct 09 '12 at 14:43
  • Hi @Carlos. `DefaultStreamedContent(InputStream stream, String contentType)` is deprecated. – Arash Jul 12 '22 at 07:51