A common complaint from Java developers when using ImageIO in Java is that it is both slow to write out images, and that the images it produces are not well optimised and have large file sizes. In this post I cover some ways to improve performance.
Option 1: Use a BufferedOutput Stream
One simple thing you can do if you are not already is to use a BufferedOutputStream, though the improvement is mostly negligible.
Option 2: Switch to a faster image format
Another possibility is to write out JPEG files rather than PNG files which is faster in Java, but as JPEG does not support transparency, this becomes a bug if your images contain colors with alpha.
Option 3: Switch from ImageIO to a faster alternative
Option 4: Use threads
One final technique is that you can write images out on a separate thread, though this may not fit your use case. The key here is that ImageIO.write() is largely bound by IO and as such, whilst writing out images, your CPU is spending most of the time simply waiting for the disk to write the image out. This is time that your CPU could spend doing other tasks, such as generating the next image that needs to be written out.
A problem with this solution is that ImageIO is not thread safe, which is why I recommend using an ExecutorService with a single thread (or switching to JDeli which is thread-safe). In order for your application to end successfully, you will need to wait for any images to finish being output.
If you have any suggestions for how to improve the performance of ImageIO.write(), please feel free to share it in the comments.
Why use JDeli to read and write Images in Java?
JDeli offers a range of advantages over ImageIO and alternatives, including:
- prevent heap related JVM crashes
- support for additional image formats such as Heic
- reduce output file size
- improve read/write performance
- create smaller files
- control over output
- support threading
- superior image scaling algorithms