If you’ve been using the imageIO.write method to save JPEG images, you may notice that some image lose quality. This is because you can’t instruct the imagIO.write method to apply a certain compression quality to the images.
Using the imageIO.write method to save JPEG images is simple, but doesn’t give you the control you need to adjust compression quality:
ImageIO.write(bufferedimage, "jpeg", file);
If you’re willing to write a few extra lines of code, the Java Imaging API offers another way.
The following imports will be necessary:
import java.io.File;
import java.util.Iterator;
import javax.imageio.*;
import javax.imageio.stream.*;
You first need to enumerate the image writers that are available to your configuration:
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
Then, choose the first image writer available (unless you want to choose a specific writer) and create an ImageWriter instance:
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
Now, we can set the compression quality:
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
Output the file:
File file = new File(OUTPUTFILE);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(BUFFEREDIMAGE, null, null);
writer.write(null, image, iwp);
writer.dispose();