Convert BufferedInputStream into Image
The challenge arises when attempting to transform a Blob retrieved from a database into a visible image. In this specific case, the Blob is stored as a BufferedInputStream, and converting it directly into an image via ImageIO.read returns null.
Addressing the Issue
Suggested Code Modifications:
public BufferedImage getPhoto(Connection con) throws IOException, SQLException { Blob blob = getPhoto(con); BufferedImage image = null; byte[] data; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = blob.getBinaryStream()) { int nRead; byte[] buffer = new byte[4096]; while ((nRead = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, nRead); } data = baos.toByteArray(); image = ImageIO.read(new ByteArrayInputStream(data)); } catch (SQLException | IOException e2) { e2.printStackTrace(); } return image; }
By implementing these modifications, the Blob is retrieved correctly, converted into a ByteArrayInputStream, and read as an image using ImageIO.read.
The above is the detailed content of How to Convert a BufferedInputStream Blob from a Database into a Visible Image?. For more information, please follow other related articles on the PHP Chinese website!