Problem:
How can I convert a BufferedInputStream object, retrieved from a database, into a BufferedImage? The existing code returns a null image.
Solution:
Example:
The following Java code uses Blob#getBinaryStream to read an image from the database and convert it to a 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; } }
The above is the detailed content of How to Convert a BufferedInputStream from a Database to a BufferedImage?. For more information, please follow other related articles on the PHP Chinese website!