JPEGImageEncoder: Reducing the size of the JPEG without resizing the Image
Posted on 2007-04-02
I am using JPEGImageEncoder in order to encode a BufferedImage into a JPEG file.
The problem is that I would like to restrict the files size to a maximum of 200KB, without affecting the height/widht of the image. So I guess that the only option that is left is quality.
The code I am using is something like:
BufferedImage thumbImage = new BufferedImage(
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
imageOut = new FileOutputStream(yetAnOtherFile);
out = new BufferedOutputStream(imageOut);
encoder = JPEGCodec.createJPEGEncoder(imageOut);
enparam = encoder.getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;
enparam.setQuality( (float) quality / 100.0f, false);
I also tried a do/while loop till the out file gets an accepted size, decreasing the quality in each step. It didn't work as expected. Is there an other solution to the problem ?