1

i am trying to upload images and retrieving with help of Base64 encoding & decoding

as follows

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

While decoding I am getting sometimes the following Exception

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

encoding

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?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
bharath
  • 387
  • 1
  • 11
  • 30
  • More memory is used by decoding the image to pixels than by base64 decoding. However, even that should not be a problem unless the images are really huge and the available memory is tiny. – Henry May 27 '18 at 09:58

1 Answers1

0

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

Two possible approaches:

Increase the heap size.

Unless your images are huge, you should be able to hold an image in pixel and base64 format in memory ... a few times over.

Stream the image.

Your code for reading and writing the image is loading the entire image into memory and then writing it out. You don't need to do that. Instead, you can process it in clunks:

  1. read a chuck from the source,
  2. encode or decode the Base64 data,
  3. write the encoded / decoded chunk to the destination
  4. repeat ... until the stream has been consumed.

The linked Q&A provides some illustrations of how to do this.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216