1

我使用以下方法将图像转换为 jpg。我的解决方案的问题是它会大大降低质量。

在减小文件大小的同时保持图像质量的好方法是什么?

def convertToJpg(currentImage) {
    try {
         InputStream inStreamCrop = new ByteArrayInputStream(currentImage)
         BufferedImage bufferedImage = ImageIO.read(inStreamCrop)

         // create a blank, RGB, same width and height, and a white background
         BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
               bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
         newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

         ByteArrayOutputStream baos=new ByteArrayOutputStream()
         // write to jpeg file
         ImageIO.write(newBufferedImage, "jpg", baos);
         baos.flush()
         def image = baos.toByteArray()
         baos.close()
         return image

    } catch (IOException e) {
        e.printStackTrace();
    }
}
4

1 回答 1

2

您可以通过获取ImageWriter对象并通过参数设置来控制JPEG的质量。例如:

import javax.imageio.stream.*
import javax.imageio.*

BufferedImage bufferedImage = ImageIO.read(new File("test.png"));
float quality = 0.9;
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.setOutput(new FileImageOutputStream(new File("test.jpg")));
writer.write(null, new IIOImage(bufferedImage, null, null), param);

质量参数的范围可以在 0 和 1 之间,其中 1 具有最小的压缩。尝试不同的值;我发现 0.9 是低压缩(但文件很大)的不错选择。

请注意,OpenJDK 不支持 JPEG 图像:ImageIO not able to write a JPEG file

于 2012-12-03T16:15:35.227 回答