Home > Database > Mysql Tutorial > body text

How to Convert a BufferedInputStream Blob from a Database into a Visible Image?

Linda Hamilton
Release: 2024-11-09 21:22:02
Original
958 people have browsed it

How to Convert a BufferedInputStream Blob from a Database into a Visible Image?

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

  1. Validate the InputStream: Verify that the Blob#getBytes method returns the correct length. Ensure the file contents are not truncated.
  2. Extract Binary Data Correctly: Utilize Blob#getBinaryStream instead of Blob#getBytes to retrieve the binary data, accounting for the specific characteristics of the database (e.g., H2).
  3. Bypass BufferedInputStream: Bypass the BufferedInputStream by creating a ByteArrayOutputStream and writing the binary data to it. Then create a ByteArrayInputStream from the ByteArrayOutputStream for use with ImageIO.read.

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template