Java BLOB to image file

2019-09-21 16:59发布

I have a BLOB that is retrieved from a MySQL database as follows:

Blob imageBlob;
while (rs.next()) {
    imageBlob= rs.getBlob("face");
}

after that my imageBlob is something like this: data:image/png;base64,iVBORw0KGgoAAAANSUhE................

I've been googling around but I haven't found any solution to my problem: how do I create an image file and save it on the disk from this BLOB?

标签: java image blob
2条回答
姐就是有狂的资本
2楼-- · 2019-09-21 17:29

imageBlob is storing the base64 representation of your image data. For storing that onto your disk you need to decode that base64 representation into the original binary format representation.

// Imports required
import java.util.Base64
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.imageio.ImageIO;

String imageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhE....";
String base64Data = imageData.split(",")[1]

byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
BufferedImage image = ImageIO.read(bis);

File outputFile = new File("output.png");
ImageIO.write(image, "png", outputFile);    
查看更多
来,给爷笑一个
3楼-- · 2019-09-21 17:29

First convert the Blob to BuffededImage:

Blob aBlob = rs.getBlob("Photo");
InputStream is = aBlob.getBinaryStream(0, aBlob.length());
BufferedImage image=ImageIO.read(is);

Then BufferedImage to Image:

try {
    // Retrieve Image
    File outputfile = new File("saved.png");
    ImageIO.write(image, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}
查看更多
登录 后发表回答