Convert BufferedInputStream into Image
問題涉及使用 Java 程式設計將從資料庫擷取的 Blob 物件轉換為映像。假設 Blob 包含影像數據,但轉換會產生空值。
答案
完整程式碼範例
以下程式碼片段提供如何從以下位置擷取和顯示影像的範例:使用上述考慮因素的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 物件轉換為映像時傳回空值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!