您可以使用Java ImageIO
包对许多图像格式进行压缩,这是一个示例
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<ImageWriter> 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();
}
}
您可以在此处找到有关它的更多详细信息
还有一些像这样的第三方工具
编辑:如果你想在你的应用程序中使用谷歌,它可以作为Apache或Nginx的Web服务器模块,你可以在这里找到如何为你的网站配置它PageSpeed
https://developers.google.com/speed/pagespeed/module/
但是,如果要将C++库集成到应用程序中,可以在此处找到它的生成说明。PageSpeed
https://developers.google.com/speed/pagespeed/psol
它在这里还有一个Java客户端。
https://github.com/googleapis/google-api-java-client-services/tree/main/clients/google-api-services-pagespeedonline/v5