Go to content Go to menu

What happens is that you read in an image with ImageIO, but then any kind of manipulation of the image is very slow.


 // read in the image
 BufferedImage bufferedImageOriginal = 
         ImageIO.read( bufferedinputstream );

// get a byte output stream and wrap it in a buffered //output stream ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); BufferedOutputStream bufferedoutputstream = new BufferedOutputStream( bytearrayoutputstream ); // write the image to the output stream ImageIO.write( bufferedImageOriginal, “jpg”, bufferedoutputstream ); // get the byte array from the byte output stream byte[] byteData = bytearrayoutputstream.toByteArray(); // generate the small thumbnail stopwatch.reset(); stopwatch.start(); Image imageSmall = bufferedImageOriginal.getScaledInstance( 50, -1, BufferedImage.SCALE_SMOOTH ); BufferedImage bufferedimageSmall = convert( imageSmall ); bytearrayoutputstream = new ByteArrayOutputStream(); bufferedoutputstream = new BufferedOutputStream( bytearrayoutputstream ); ImageIO.write( bufferedimageSmall, “jpg”, bufferedoutputstream ); byte[] byteDataSmall = bytearrayoutputstream.toByteArray();

The reading of the image will go very fast, but the scaling will be super slow (i.e.. 0.3s to read and 22.3 to scale).

As it so happens, this is a problem with the color space of the original image. It’s not in the sRGB color space and, as a result, it does a transform on each pixel to get it into the sRGB colorspace, [Bug ID: 4705399](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4705399).

Forcing ImageIO to read the image in with the sRGB color space seems to solve this issue.



public static BufferedImage readImage(Object source) throws IOException {

ImageInputStream stream = ImageIO.createImageInputStream(source); ImageReader reader = (ImageReader) ImageIO.getImageReaders(stream).next(); reader.setInput(stream); ImageReadParam param = reader.getDefaultReadParam();

ImageTypeSpecifier typeToUse = null; for (Iterator i = reader.getImageTypes(0); i.hasNext(); ) { ImageTypeSpecifier type = (ImageTypeSpecifier) i.next(); if( type.getColorModel().getColorSpace().isCS_sRGB() ) { typeToUse = type; } }

if (typeToUse!=null) param.setDestinationType(typeToUse);

BufferedImage b = reader.read(0, param);

reader.dispose(); stream.close(); return b;
}


2 Responses to "ImageIO Slow to Manipulate Images"

  1. Craig Smith Says:
    Thanks for taking the time out to explain this. I'm currently writing a Java applet for uploading images to an ftp server which involves displaying thumbnails of images. I've been puzzling for weeks over why some images were very slow to process whilst others were very quick. This solved my problems, so thanks.

    Craig
  2. Says:
    Thanks!