0

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 ?

ali muhammad
  • 13
  • 1
  • 1
  • 4
  • 2
    JPEG and PNG images *are* compressed. – Boann Apr 02 '14 at 13:03
  • I think you need to look at image slicing. Photoshop has this and it makes it an image load faster. Please check slice technique and see if that can help you. – Soley May 04 '15 at 20:00

1 Answers1

5

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();
}
Marco13
  • 53,703
  • 9
  • 80
  • 159
  • Hi Marco13, Thanks for you reply. Let me elaborate more. We are building a realstats application, there are lot of properties and each property has 10 to 30 .jpeg image. When a property is selected, its corresponding images are shown. Is there any way to compress/ reduce size the images to load fast? Let me know if you want more details – ali muhammad Apr 02 '14 at 13:49
  • Compression is usually only indirectly related to the time that is required for *loading* the images. A compressed image might load faster (because less data has to be read from the hard disk), but this would have to be validated with a benchmark (although I doubt that is is possible to *sensibly* validate this). General hints for possible optimizations (like caching or pre-loading the images in a background thread) are beyond the scope of this comment. – Marco13 Apr 02 '14 at 14:18