If the specified image file contains an image too large, in term of required memory to load it, an OutOfMemoryError
is raised. For the same reason, if the scale factor of a scaling operation would create a too large image, an OutOfMemoryError
is raised as follows:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:75)
at java.awt.image.Raster.createPackedRaster(Raster.java:467)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1032)
at java.awt.image.BufferedImage.<init>(BufferedImage.java:340)
at java.awt.image.AffineTransformOp.createCompatibleDestImage(AffineTransformOp.java:461)
at java.awt.image.AffineTransformOp.filter(AffineTransformOp.java:226)
Is it be possible to prevent this error from occurring, by performing some preliminary check? For example, if the application determines the maximum image size (in pixels) that can be loaded into memory by the amount of available memory, you could avoid performing scaling, whose resulting image would have a number of pixels greater than the determined limit.
How to handle the above problem with an image that is to be read from file? How to get the size of an image file without load it in memory? This problem could be handled using the solutions proposed in this Q&A: this solution is very fast bacause the image size is read from the file, without loading the whole image.
In summary...
The first target consists in performing a preliminary check in order to get the size of the image to show, without load the whole image:
- if the image is an image file, this can be achieved using the solution proposed in this Q&A;
- if the target image is the result of a scaling procedure, just multiply the size of the current image by the specified scale factor.
In both cases, you get the size of the image that should be loaded into memory, ie the total number of pixels. This value could be compared to a value limit. But, how to calculate this value limit? How to determine the maximum image size or the maximum number of pixels that can be loaded into memory by the amount of available memory?