将base64映像解码并存储在磁盘上(使用java)内存不足

时间:2015-01-17 15:16:52

标签: java tomcat base64 out-of-memory

我需要在磁盘上存储base64图像,但我有一个错误:"内存不足"当我将base64图像解码为byte []时。尺寸图像约为6MB 这是我的代码:

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();

请,有人建议吗?

1 个答案:

答案 0 :(得分:0)

你可以写"照片"内容到临时文件,然后使用Base64InputStream从中读取。

但是,最后,BufferedImage将整个原始图像保存在内存中。这将要求您具有足够大的堆大小以容纳此大小。您可能只需要增加Xmx值。

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