Fastest way to free BufferedImage memory

bufferedimage, java, memory

Solution

PNG is notorious slow in ImageIO. You might try getting the underlying readers and writers. Maybe write a JPEG instead with hight quality. Alternatives.

Can't you store the input files as File first, so writing with ImageIO is not needed.

For completeness sake: if you da a `BufferedImage.getGraphics()` do not forget the `dispose()`.

Problem

What is the fastest way to save a BufferedImage to disk (in order to free memory)? My Java application processes loads of images (an image is loaded to memory every ~300ms). Most of those images are discarded (gc) quite immediately, but every once in a while I need to save an image. Of course, keeping those in RAM is not a good idea, for it eats up an average 2GB JVM in minutes, and crushes the application, so I tried saving it to disk. The problem is, saving it with `ImageIO.write(img, "PNG", file)` is not sufficient enough, because it sometimes takes (on my i7 machine) 5-10 second per 12MB image to process and save, and still doesn't free the memory fast enough. Is there another format that might perform faster? EDIT: I don't care to lower resolution or loose image data at reasonable level.

Original source