简体   繁体   中英

Fastest way to Read/Write JPG Images without losing Quality?

I have JPG image files, which I want to load into a BufferedImage and later write the BufferedImage back into a JPG file. Here is what I am currently doing.

Is there a better way not to lose quality and make read/write faster?

Read:

BufferedImage image = ImageIO.read(new File(storagePath + fileName + extension));

Write:

BufferedImage image = // some jpg image         

Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
if (iter.hasNext()) {
    ImageWriter writer = (ImageWriter) iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

    File outFile = new File(storagePath + fileName + extension);
    FileImageOutputStream output = new FileImageOutputStream(outFile);
    writer.setOutput(output);
    IIOImage iioImage = new IIOImage(image, null, null);
    writer.write(null, iioImage, iwp);
}

You can minimize the loss in quality in recompressing JPEG by using the same quantization tables used to correct the original image. It is still possible to get single bit errors from rounding but you can get it pretty close.

The problem is how to get the quantization tables. If your encoded will allow you to specify them, you can pull the values out of the source image. Otherwise, you have to hope that the images were originally encoded using the same encoder.

"Quality Values" are not part of JPEG. They are a method for selecting quantization tables used by some encoder. The LIBJPEG is the most common encoder but there are others out there that do things differently.

PNG encoding is generally slower than JPEG.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM