Search code examples
javajpegimage-compression

Changing Image resolution without resizing in Java


I want to compress a jpeg image, that is, decrease its resolution, without resizing it in any way. Is there any good Java library that will help me doing it? There are lots of similar posts in SO, but most of them end up resizing the image as well.

If not, how can I do it programatically? Say, for an argument of 0.9, the image's resolution will decrease by a factor of 0.1...


Solution

  • Typically "resolution" means size. Do you mean the JPEG quality instead? That is the only way I can think of to compress it without resizing it.

    If so, you can use the Java2D ImageIO API. Something like the following would work (adapted from this page):

    BufferedImage bufferedImage = ImageIO.read(...);
    
    ImageWriter writer = (ImageWriter)ImageIO.getImageWritersByFormatName("jpeg").next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(...);
    
    File file = new File(...);
    FileImageOutputStream output = new FileImageOutputStream(file);
    writer.setOutput(output);
    IIOImage image = new IIOImage(bufferedImage, null, null);
    writer.write(null, image, iwp);
    writer.dispose();
    

    Unfortunately, I don't think there's a way to get the existing JPEG quality of an image, so you'll have to use some fixed value for the compression quality.