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;
}