Home > Database > Mysql Tutorial > body text

Why is my Java code converting a Blob object to an image returning a null value?

Patricia Arquette
Release: 2024-11-09 16:54:02
Original
324 people have browsed it

Why is my Java code converting a Blob object to an image returning a null value?

Convert BufferedInputStream into Image

The question pertains to converting a Blob object retrieved from a database into an image using Java programming. The Blob is assumed to contain image data, but the conversion is resulting in a null value.

Answer

  • Verify Uploaded Blob: Ensure that the uploadedInputStream contains valid image data. Save it to a file using ImageIO.write and then read it back to verify its integrity.
  • Length Mismatch: Note that Blob#length returns a long while Blob#getBytes expects an int. Verify the length value to avoid potential truncation.
  • Alternative Retrieval: H2 database's Blob contents may not be stored in memory. Consider using getBinaryStream instead to retrieve the image data.

Full Code Example

The following code snippet provides an example of how to retrieve and display an image from an H2 database using the aforementioned considerations:

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class ImageDatabaseExample {

    public static void main(String[] args) {
        try {
            // Load sample image into database
            saveImage();

            // Retrieve and display image
            loadImage();
        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    protected static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("org.h2.Driver");
        return DriverManager.getConnection("jdbc:h2:d:\Image", "sa", "");
    }

    protected static void saveImage() throws IOException, ClassNotFoundException, SQLException {
        Connection con = getConnection();
        PreparedStatement stmt = null;
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream bais = null;

        try {
            baos = new ByteArrayOutputStream();
            BufferedImage img = ImageIO.read(new File("/path/to/file"));
            ImageIO.write(img, "png", baos);
            baos.close();

            bais = new ByteArrayInputStream(baos.toByteArray());

            stmt = con.prepareStatement("insert into images (image) values (?)");
            stmt.setBinaryStream(1, bais);
            stmt.executeUpdate();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        }
    }

    protected static void loadImage() throws IOException, ClassNotFoundException, SQLException {
        Connection con = getConnection();
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            stmt = con.prepareStatement("select image from images");
            rs = stmt.executeQuery();

            while (rs.next()) {
                Blob blob = rs.getBlob(1);
                BufferedImage img = ImageIO.read(blob.getBinaryStream());
                JOptionPane.showMessageDialog(null, new JScrollPane(new JLabel(new ImageIcon(img))));
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        }
    }
}
Copy after login

The above is the detailed content of Why is my Java code converting a Blob object to an image returning a null value?. 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