How can I compress images using java?

前端 未结 3 1119
闹比i
闹比i 2020-12-17 10:49

From pagespeed I am getting only image link and possible optimizations in bytes & percentage like, Compressing and resizing https://example.com/…ts/xyz.jpg?036861 could

3条回答
  •  無奈伤痛
    2020-12-17 11:21

    You can use Java ImageIO package to do the compression for many images formats, here is an example

    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Iterator;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    
    public class Compresssion {
    
      public static void main(String[] args) throws IOException {
    
        File input = new File("original_image.jpg");
        BufferedImage image = ImageIO.read(input);
    
        File compressedImageFile = new File("compressed_image.jpg");
        OutputStream os = new FileOutputStream(compressedImageFile);
    
        Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = (ImageWriter) writers.next();
    
        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        writer.setOutput(ios);
    
        ImageWriteParam param = writer.getDefaultWriteParam();
    
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.05f);  // Change the quality value you prefer
        writer.write(null, new IIOImage(image, null, null), param);
    
        os.close();
        ios.close();
        writer.dispose();
      }
    }
    

    You can find more details about it here

    Also there are some third party tools like these

    • https://collicalex.github.io/JPEGOptimizer/
    • https://github.com/depsypher/pngtastic

    EDIT: If you want to use Google PageSpeed in your application, it is available as web server module either for Apache or Nginx, you can find how to configure it for your website here

    https://developers.google.com/speed/pagespeed/module/

    But if you want to integrate the PageSpeed C++ library in your application, you can find build instructions for it here.

    https://developers.google.com/speed/pagespeed/psol

    It also has a Java Client here

    https://developers.google.com/api-client-library/java/apis/pagespeedonline/v1

提交回复
热议问题