0

I have the code below on a tomcat server. The goal is to save in .jpg an image (that is sent in String) and create the equivalent thumbnails. The goal is properly achieved nevertheless I noticed that at every execution (even after trying to set almost all used variables "null"), the server memomy increases by 6 Megabytes which are never freed. Since I have a very small RAM's server, this is really problematic. By the way images sent are close to 30 kilobytes only.

public boolean saveImage(String picInString)
        throws IOException {
    byte[] bytes = null;

    try {
        bytes = Base64.decode(picInString);
    } catch (Base64DecodingException e) {
        e.printStackTrace(System.out);
    }

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("png");

    ImageReader reader = (ImageReader) readers.next();
    Object source = bis;
    ImageInputStream iis = ImageIO.createImageInputStream(source);
    Graphics2D g2 = null;

    try {
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();

        Image image = reader.read(0, param);

        // got an image file
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
                image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        // bufferedImage is the RenderedImage to be written

        g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);

        ImageIO.write(bufferedImage, "jpg", new File("/image.jpg"));

            ImageIO.write(Scalr.resize(MyImageClass.cropImage(bufferedImage), 100, 100),
                            "jpg", new File("/image_mini.jpg"));


        bufferedImage.flush();
        bufferedImage = null;

    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (reader != null) {
            reader.dispose();
        }
        if (g2 != null) {
            g2.dispose();
        }
        bis.close();
        iis.close();
        reader = null;
        bis = null;
        iis = null;
    }

    return false;
}

Any help will be appreciated!

user3793589
  • 418
  • 3
  • 14

2 Answers2

0

Someone gave me a clue to the answer but I am not able to see the comment anymore. Actually, setting the variable "image" to null at the end of the process has solved the issue.

user3793589
  • 418
  • 3
  • 14
-1

You shouldn't tame an image as it is. You should down sample it like it is done in android. Scaling is a must to prevent memory errors and exceptions. This SO questions is the solution to all your problems. How to improve the performance of g.drawImage() method for resizing images

Community
  • 1
  • 1
Parth Sane
  • 587
  • 7
  • 24