0

我想显示一张动态照片,我将图像的内容作为 blob 存储在数据库中,照片实体中的内容类型是字节数组 (byte[])。我尝试了两种不同的方法,但都没有用。

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;
}

并在查看页面中:

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

所以有人可以帮我让它工作!

4

1 回答 1

2

您首先必须从数据库中检索 blob。

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;
}

有关 Blob 类的更多信息。

于 2012-10-08T00:06:27.090 回答