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

标签 java image out-of-memory

我正在尝试上传图像并在 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. 从源代码中读取一个chuck,
  2. 对 Base64 数据进行编码或解码,
  3. 将编码/解码的 block 写入目标
  4. 重复...直到流被消耗。

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

关于将图像编码和解码为 Base64 时出现 java 内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550869/

相关文章:

java - 如何更改字符串中的字符 - 替换字母java

java - 如何编写一个呈现 JSP 片段列表的 JSP,而无需 IF 切换代码

java - 当有两个接口(interface)时指定 RMI 端点地址

java - 如何将一个 PNG 图像用于多个 Sprite ?

android - 633632 字节分配内存不足

java - 设置类路径但Java程序(使用Apache外部jar)无法在CMD线路上运行

android - 如何在android中使用fancycoverflow获取位置

python - img [y:y + h,x:x + w]坐标系的工作方式

android - 致命信号 11 (SIGSEGV) 位于 0x00000000(代码=1),线程 27830(ple.myfragexample)——仅适用于 Android 4.1.2

android - 从android中的图库获取图像时android中的java.lang.OutOfMemoryError