package com.pap.base.util.image;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
public class JPGCompressTest {
// 输入图像绝对路径、输出图像绝对路径、期望的图像大小
public static void convertJpg(String inputImagePath, String outputImagePath, double targetSizeBytes) throws IOException {
File inputFile = new File(inputImagePath);
File outputFile = new File(outputImagePath);
long currentSize = inputFile.length();
float quality = 0.5f;
while (currentSize > targetSizeBytes && quality > 0.1f) {
BufferedImage bufferedImage = ImageIO.read(inputFile);
writeJpgWithQuality(bufferedImage, outputFile, quality);
currentSize = outputFile.length();
quality -= 0.005f;
}
while (currentSize < targetSizeBytes) {
BufferedImage bufferedImage = ImageIO.read(inputFile);
writeJpgWithQuality(bufferedImage, outputFile, quality);
currentSize = outputFile.length();
quality += 0.005f;
}
}
private static void writeJpgWithQuality(BufferedImage image, File outputFile, float quality) throws IOException {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (writers.hasNext()) {
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
try (FileImageOutputStream output = new FileImageOutputStream(outputFile)) {
writer.setOutput(output);
writer.write(null, new javax.imageio.IIOImage(image, null, null), param);
} finally {
writer.dispose();
}
}
}
}
评论