我正在尝试上传图像并在 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 格式的图像......多次。
流式传输图像。
用于读取和写入图像的代码是将整个图像加载到内存中,然后将其写出。你不需要这样做。相反,您可以一次性处理它:
- 从源代码中读取一个chuck,
- 对 Base64 数据进行编码或解码,
- 将编码/解码的 block 写入目标
- 重复...直到流被消耗。
链接的问答提供了一些如何执行此操作的说明。
关于将图像编码和解码为 Base64 时出现 java 内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550869/