I use MySql db with images in blob and try to display them on my JSF page using PrimeFaces galleria. On my page I see this galleria, but images aren't displayed. I see only small green icons in a corner of every image. I get this problem only using DB. If my images are in my file system, everything will be OK. Can someone explain why I can't see images from DB? I wrote this code:
Galleria:
<p:galleria value="#{imagesView.images}" var="image" panelWidth="500" panelHeight="250" showCaption="true">
<p:graphicImage value="#{image}" alt="Image Description" title="Title"/>
</p:galleria>
ImagesView:
@ManagedBean
public class ImagesView {
private List<StreamedContent> images;
@PostConstruct
public void init() {
images = new ArrayList<>();
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
int itemId = Integer.parseInt(request.getParameter("item_id"));
for (int i = 1; i <= 2; i++) {
images.add(new GraphicImage().getImageFromDB(i, itemId)); //It's so simple because I need it just for test and that's all
}
}
public List<StreamedContent> getImages() {
return images;
}
}
GraphicImage:
@RequestScoped
class GraphicImage implements Serializable {
StreamedContent getImageFromDB(int id, int itemId) {
if (FacesContext.getCurrentInstance().getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
byte[] image = DBUtils.getImage(id, itemId);
return new DefaultStreamedContent(new ByteArrayInputStream(image), "image/jpg");
}
}
}
DBUtils method:
public static byte[] getImage(int id, int itemId) {
byte[] image = null;
ResultSet resultSet = null;
try (Connection connection = DataBase.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT content FROM images WHERE id = ? AND item_id = ?")) {
statement.setInt(1, id);
statement.setInt(2, itemId);
resultSet = statement.executeQuery();
resultSet.next();
image = resultSet.getBytes("content");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return image;
}