java 将图像编码和解码为 base64 时出现内存不足异常

java out of memory exception while encoding and decoding image in to base64

我正在尝试上传图片并借助 Base64 encoding & decoding

进行检索

如下

解码

if (imgString != null ) {  
    BufferedImage image = null;
    byte[] imageByte;

    BASE64Decoder decoder = new BASE64Decoder();
    imageByte = decoder.decodeBuffer(imgString);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    image = ImageIO.read(bis);
    bis.close();

    String realPath  = request.getSession().getServletContext().getRealPath("/resources/images/"+studentDetails.getFirstname()+".png");

    File outputfile = new File(realPath);    
    ImageIO.write(image, "png", outputfile); 
        studentDetails.setStuImg(outputfile.toString());
    }

解码时有时会出现以下异常

May 27, 2018 3:04:27 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [spring] in context with path [/campasAdmin] threw exception [Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause java.lang.OutOfMemoryError: Java heap space

编码

if (imagePath != null && imagePath.length() > 0) {      
    byte[] bytes = Files.readAllBytes(Paths.get(imagePath));
    encodedFile = Base64.getEncoder().encodeToString(bytes);
}

有什么解决办法吗?我该如何避免?

What is the solution to it? How would I avoid it?

两种可能的方法:

增加堆大小。

除非你的图像很大,否则你应该能够在内存中保存像素和 base64 格式的图像......多过几次。

流式传输图像。

您读取和写入图像的代码是将整个图像加载到内存中,然后将其写出。你不需要那样做。相反,您可以笨拙地处理它:

  1. 从源码中读取一个卡盘,
  2. 编码或解码Base64数据,
  3. 将编码/解码的块写入目标
  4. 重复...直到流被消耗。

链接的问答提供了一些说明如何执行此操作。