>데이터 베이스 >MySQL 튜토리얼 >Java 코드가 Blob 객체를 null 값을 반환하는 이미지로 변환하는 이유는 무엇입니까?

Java 코드가 Blob 객체를 null 값을 반환하는 이미지로 변환하는 이유는 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-11-09 16:54:02419검색

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

BufferedInputStream을 이미지로 변환

질문은 Java 프로그래밍을 사용하여 데이터베이스에서 검색된 Blob 개체를 이미지로 변환하는 것과 관련이 있습니다. Blob에 이미지 데이터가 포함되어 있다고 가정하지만 변환 결과 null 값이 발생합니다.

답변

  • 업로드된 Blob 확인: UploadInputStream에 유효한 이미지 데이터가 포함되어 있는지 확인하세요. ImageIO.write를 사용하여 파일에 저장한 다음 다시 읽어서 무결성을 확인하세요.
  • 길이 불일치: Blob#length는 long을 반환하지만 Blob#getBytes는 int를 기대합니다. 잘림 가능성을 방지하려면 길이 값을 확인하세요.
  • 대체 검색: H2 데이터베이스의 Blob 콘텐츠는 메모리에 저장되지 않을 수 있습니다. 이미지 데이터를 검색하려면 대신 getBinaryStream을 사용하는 것이 좋습니다.

전체 코드 예

다음 코드 조각은 다음 코드 조각에서 이미지를 검색하고 표시하는 방법에 대한 예를 제공합니다. 앞서 언급한 고려 사항을 사용한 H2 데이터베이스:

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();
            }
        }
    }
}

위 내용은 Java 코드가 Blob 객체를 null 값을 반환하는 이미지로 변환하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.