I have images stored in a database in the form of ImageIcons that I would like to serve to our web page, however for large images I am getting out of memory exceptions.
Here is how I currently do it,
[Edit] I expanded my ImageUtilities to provide a non transparent BufferedImage which simplifies the code,
BufferedImage rgbbi = ImageUtilities.toBufferedImage(icon.getImage());
ServletOutputStream out = null;
try {
// Get the Servlets output stream.
out = responseSupplier.get().getOutputStream();
// write image to our piped stream
ImageIO.write(rgbbi, "jpg", out);
} catch (IOException e1) {
logger.severe("Exception writing image: " + e1.getMessage());
} finally {
try {
out.close();
} catch (IOException e) {
logger.info("Error closing output stream, " + e.getMessage());
}
}
The exceptions that are being thrown are the following,
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.JPEGImageDecoder.sendPixels(JPEGImageDecoder.java:97)
at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:119)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
...
Is there a way I can rewrite this to stream the output of ImageIO.write
and limit its buffer size somehow?
[Edit]
I can't just increase the heap size either, the images I need to serve are in the range of 10000x7000 pixels, as a byte array that works out (10000px x 7000px x 24bits)
280MB. I think that is an unreasonable heap size to allocate for image conversion in a servlet.
An example Image Large