图片压缩的重要性
1. 提升网页加载速度
2. 节省存储空间
3. 降低数据传输成本
Java图片质量压缩方法
1. 使用ImageIO进行压缩
ImageIO是Java提供的一个用于处理图像的类库,它可以轻松地读取和写入各种图像文件格式。
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageCompression {
public static void compressImage(String inputImagePath, String outputImagePath, float quality) throws IOException {
File inputFile = new File(inputImagePath);
BufferedImage image = ImageIO.read(inputFile);
File outputFile = new File(outputImagePath);
ImageIO.write(image, "jpg", outputFile);
}
}
2. 使用WebP格式
import org.webp.java.WebPImage;
public class WebPCompression {
public static void compressImage(String inputImagePath, String outputImagePath, float quality) throws IOException {
WebPImage webPImage = WebPImage.fromFile(new File(inputImagePath));
webPImage.toFile(outputImagePath, quality);
}
}
3. 使用第三方库
import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.geometry.Coordinates;
import net.coobird.thumbnailator.geometry.Positions;
public class ThumbnailatorCompression {
public static void compressImage(String inputImagePath, String outputImagePath, float quality) throws IOException {
BufferedImage image = ImageIO.read(new File(inputImagePath));
BufferedImage compressedImage = Thumbnailator.createThumbnail(image, Coordinates.from(Positions.CENTER), (int) (image.getWidth() * quality));
ImageIO.write(compressedImage, "jpg", new File(outputImagePath));
}
}