Michael
Michael

Reputation: 33307

How can I convert png/gif/jpg in grails to jpg maintaining a high quality in the image?

I use the following method for converting images to jpg. The problem with my solution is that it will reduce the quality to much.

What is a good way to maintain quality of the image, while reducing the file size?

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();
    }
}

Upvotes: 1

Views: 1794

Answers (1)

ataylor
ataylor

Reputation: 66099

You can control the quality of the JPEG by getting an ImageWriter object and setting it through the parameters. For example:

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);

The quality parameter can range between 0 and 1, with 1 having the least compression. Try different values; I've found 0.9 is a good choice for low compression (but large file sizes).

Note that JPEG images are not supported with OpenJDK: ImageIO not able to write a JPEG file

Upvotes: 2

Related Questions