JPEG quality and size reduction when using ImageIO.write


So what is the general and easiest way to read a JPEG from a File, modify it and then write it back to the File
 
try{
                 File testimage = new File(“/opt/images/testimage.jpg”);
                 BufferedImage bufimg = ImageIO.read(testimage);
                 //MODIFY IMAGE
                 File outfile =new File(“/opt/images/modified.jpg”);
                 ImageIO.write(bufimage, “jpg”, outfile);
} catch (IOException ex) {
System.out.println(“Exception : ” + ex);
}
 
 
but the above method drastically reduces quality and hence the size of the image sometimes by 70%, so if quality of the final image is not your concern then its ok. But if you want to retain the quality of the original JPEG then following(Inspired by this post) is the way to set the Quality for the final output JPEG.
 
try{
                File testimage = new File(“/opt/images/testimage.jpg”);

                BufferedImage bufimg = ImageIO.read(testimage);
                File outfile =new File(“/opt/images/modified.jpg”);
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(“jpeg”);
                ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(1.0f);
                writer.setOutput(outfile);
                writer.write(null, new IIOImage(bufimg ,null,null),iwp);
                writer.dispose();
} catch (IOException ex) {
System.out.println(“Exception : ” + ex);
}
 
 
So the point here is while reading the JPEG things go very well but while writing ImageIO.write sets the default Quality and hence the reduction in the size of the final JPEG, so by setting the quality explicitly the problem is averted.
Further Reading:
Advertisements

About Dominic

J for JAVA more about me : http://about.me/dominicdsouza
This entry was posted in Thechy Stuff and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s