High memory consumption with BufferedImage object

We used BufferedImage objects in our application for rendering PNG images, unfortunately, after performing certain operations, such as rotating and resizing images (in turn, these operations create and return a new BufferedImage object with an updated length and width) heap java size becomes high and high to cause OutofMemory error.

Even after closing the current panel, the GC does not restore the memory consumed by this BufferedImage object, I read a lot of threads that mention old versions of the JDK itself (up to 1.5) that have a memory leak in BufferedImage, but did not find a work around or fix this. Even in later versions of the JDK, for example, when driving, we use jdk1.6.0_26 and we can still see this problem.

Would it be nice if anyone can offer some tips to stop a memory leak using the BufferedImage object or any other alternative implementations for this object?

+4
source share
3 answers

You should try using AffineTransform with Graphics2D drawImage (or any other that accepts an AffineTransform object).

These AffineTransform objects are transformation matrices, they can store all operations with images in one matrix, and then apply this transformation matrix to the image in 1 transformation.

You can do any of four things with a transformation matrix:

  • transfer
  • rotation
  • Scale
  • shear

Also in this way you do not have to create a new BufferedImage every time you apply a transformation.

+1
source

You can use BigBufferedImage instead of BufferedImage. BigBufferedImage has the real benefit that it saves the image on your hard drive, and you don't have to worry about heap size or physical memory limit. It can store a maximum of 2,147,483,647 pixels (or 46.340 x 46.340 pixels).

Create az empty BigBufferedImage:

BigBufferedImage image = BigBufferedImage.create( tempDir, width, height, type); 

Load an existing image in BigBufferedImage:

  BigBufferedImage image = BigBufferedImage.create( imagePath, tempDir, type); 

Display part of image:

  part = image.getSubimage(x, y, width, height); 

For more information on large image processing, read this article .

0
source

Here we have the same problem. We use many instances of JChart, and memory leaks easily.

All leaks occur in java.awt.image.BufferedImage .

The solution we found:

  • Remove the Object BufferedImage link in your case. object.remove() or object = null
  • Call the garbage collector System.gc() . It will really free your memory.

But using a GC is a bit expensive.

-3
source

Source: https://habr.com/ru/post/1398835/


All Articles