我想要显示动态照片 我将图像的内容存储为数据库中的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}"/>
有人可以帮助我让它发挥作用!!
答案 0 :(得分: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;
}