From our application we fetch images (jpeg/png) from a third party service, after download we want to save these images as compressed.
Can any one please guide how to compress images in Java ?
From our application we fetch images (jpeg/png) from a third party service, after download we want to save these images as compressed.
Can any one please guide how to compress images in Java ?
JPG and PNG images already are compressed, so it's not entirely clear what your intention is. However, in general, you can write images with ImageIO
:
ImageIO.write(image, "jpg", outputStream);
(or "png"
, analogously). By default, this does not allow you to select the compression level (that is, the trade-off between file size and image quality). In order to write a JPG file with a different than the default compression, you can use a utility method like this:
public static void writeJPG(
BufferedImage bufferedImage,
OutputStream outputStream,
float quality) throws IOException
{
Iterator<ImageWriter> iterator =
ImageIO.getImageWritersByFormatName("jpg");
ImageWriter imageWriter = iterator.next();
ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(quality);
ImageOutputStream imageOutputStream =
new MemoryCacheImageOutputStream(outputStream);
imageWriter.setOutput(imageOutputStream);
IIOImage iioimage = new IIOImage(bufferedImage, null, null);
imageWriter.write(null, iioimage, imageWriteParam);
imageOutputStream.flush();
}