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?
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);
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) {
...
}