1

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Deyan koba
  • 238
  • 1
  • 4
  • 15

2 Answers2

2

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);    
pulkit-singhal
  • 845
  • 5
  • 15
0

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) {
    ...
}
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30
Amit
  • 1,540
  • 1
  • 15
  • 28