代码之家  ›  专栏  ›  技术社区  ›  bharath

Java内存缺省异常,同时编码和解码图像到Base64(复制)

  •  1
  • bharath  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我正在尝试上载图像并在的帮助下检索 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());
        }
    

    在解码时,我有时会遇到以下异常

    2018年5月27日下午3:04:27 org.apache.catalina.core.standardwrappervalve invoke 严重的:servlet(Services)(Servlet)在上下文中使用PATH [/CAMPASADMI]抛出异常[处理程序调度失败;嵌套异常是JavaLang.OutOfMeMyLogError:Java堆空间],有根本原因 JavaLang.OutOfMeMyLogError:Java堆空间

    编码

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

    解决方法是什么?我该如何避免?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Stephen C    6 年前

    解决方法是什么?我该如何避免?

    两种可能的方法:

    增加堆大小。

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

    传输图像。

    读写图像的代码将整个图像加载到内存中,然后再将其写出。你不需要这么做。相反,您可以用沉闷的声音处理它:

    1. 从源头读一个查克,
    2. 对base64数据进行编码或解码,
    3. 将编码/解码块写入目标
    4. 重复…直到流被消耗。

    链接的Q&A提供了一些如何执行此操作的说明。