Reputation: 288
I have a Blob
object retrieved from a MySQL database by calling ResultSet.getBlob
.
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?
Upvotes: 1
Views: 17343
Reputation: 1560
First convert the Blob to BuffededImage:
Blob aBlob = rs.getBlob("Photo");
InputStream is = aBlob.getBinaryStream(1, 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) {
...
}
Upvotes: 0
Reputation: 847
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);
Upvotes: 2