0
votes

i need to store on disk a base64 image but i have an error: "Out of memory" when i decode base64 image into byte[]. The size image is about 6MB This is my code:

byte[] decodedBytes = DatatypeConverter.parseBase64Binary(photo); //HERE I HAVE THE ERROR!!
log.debug("binary ok");
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));    

String nomeEdata = String.valueOf(Calendar.getInstance().getTimeInMillis() + ".jpg");
String nomeImg = resourceBundle.getString("schede.pathSaveImage") + nomeEdata;

File outputfile = new File(nomeImg);
ImageIO.write(bfi , "png", outputfile);
bfi.flush();

Please, Any suggests?

1
Would it be possible to show us what data type photo is and how you obtained it? - Jose Martinez

1 Answers

0
votes

You could write the "photo" content to a temporary file and then read from it using a Base64InputStream.

In the end, however, the BufferedImage will have the entire raw image in memory. This will require that you have a heap size large enough to accommodate this. You may just have to increase the Xmx value.

final BufferedImage bi = ImageIO.read(new Base64InputStream(new ReaderInputStream(new StringReader(photo), "ascii"));

final File file = ...
final FileOutputStream fos = new FileOutputStream(file);
try
{
    ImageIO.write(bi, "png", new Base64OutputStream(fos));
}
finally 
{
    fos.close();
}

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReaderInputStream.html