如何将grails中的png / gif / jpg转换为jpg,保持图像的高质量?

时间:2012-12-03 09:27:11

标签: java grails image-processing jpeg image-resizing

我使用以下方法将图像转换为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();
    }
}

1 个答案:

答案 0 :(得分: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