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
                 File testimage = new File(“/opt/images/testimage.jpg”);
                 BufferedImage bufimg =;
                 //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.
                File testimage = new File(“/opt/images/testimage.jpg”);

                BufferedImage bufimg =;
                File outfile =new File(“/opt/images/modified.jpg”);
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(“jpeg”);
                ImageWriter writer =;
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                writer.write(null, new IIOImage(bufimg ,null,null),iwp);
} 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:

About Dominic

J for JAVA more about me :
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: Logo

You are commenting using your 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 )

Connecting to %s