JPEG is a lossy image compression format which discards information that the human eyes can't notice very well. However, depending on the image quality settings when compressing the image, compression artifacts, such as blockiness and smudging can become visible -- this is the reason behind the image not appearing to be clear.
It may be possible that the ImageIO.write
method is saving the JPEG with a lower quality setting than necessary to keep the image looking good enough.
In order to set the quality setting higher, it will be necessary to use the ImageWriteParam
to specify the image quality settings, then use the ImageWriter
to output the JPEG.
For example:
// Get a writer for JPEG.
ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next();
iw.setOutput(new FileImageOutputStream(outputFile));
// Set the compression quality to 0.9f.
ImageWriteParam iwParam = iw.getDefaultWriteParam();
iwParam.setCompressionQuality(0.9f);
// Write image
iw.write(null, new IIOImage(imageToWrite, null, null), iwParam);
Methods of interest:
That said, as the other answers mention, JPEG is unsuitable for compression of text and illustrations. If the goal is to preserve the image quality, but the file size can be bigger than with compression with JPEG, then using an lossless image compression format such as PNG would preserve the image quality as it is, without any loss. However, in many cases, the file size of a PNG file will be larger than a JPEG. (But this is not always the case.)
The general rule of thumb is, for photographs and other realistic images, lossy compression formats such as JPEG will work well for the file size vs. quality trade off, while lossless compression formats such as PNG will work better for illustrations and line art, where there are large areas of similar color with little gradient effects.