问题:
如何转换从数据库检索的 BufferedInputStream 对象,到 BufferedImage 中?现有代码返回空图像。
解决方案:
示例:
以下 Java 代码使用 Blob#getBinaryStream 读取图像从数据库中获取并将其转换为 BufferedImage:
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.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.imageio.ImageIO; public class ImageDatabaseHelper { private Connection con; public BufferedImage loadImage(int imageId) throws IOException, SQLException { PreparedStatement stmt = null; ResultSet rs = null; BufferedImage image = null; try { stmt = con.prepareStatement("select image from images where id = ?"); stmt.setInt(1, imageId); rs = stmt.executeQuery(); while (rs.next()) { Blob blob = rs.getBlob(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ByteArrayInputStream bais = new ByteArrayInputStream(blob.getBinaryStream())) { ImageIO.read(bais).writeTo(baos); } image = ImageIO.read(new ByteArrayInputStream(baos.toByteArray())); } } finally { try { rs.close(); } catch (Exception e) { } try { stmt.close(); } catch (Exception e) { } } return image; } }
以上是如何将 BufferedInputStream 从数据库转换为 BufferedImage?的详细内容。更多信息请关注PHP中文网其他相关文章!