package com.dji.sample.territory.utils;
|
|
import javax.imageio.ImageIO;
|
import javax.imageio.ImageWriteParam;
|
import javax.imageio.ImageWriter;
|
import javax.imageio.stream.ImageOutputStream;
|
import javax.imageio.stream.MemoryCacheImageOutputStream;
|
import java.awt.*;
|
import java.awt.image.BufferedImage;
|
import java.io.*;
|
import java.nio.file.Files;
|
import java.nio.file.StandardCopyOption;
|
|
public class ImgZipUtil {
|
/**
|
* 图片压缩
|
*
|
* @return
|
* @throws IOException
|
*/
|
public static File compressImage(File inputFile, int targetSizeKB) throws IOException {
|
BufferedImage image = ImageIO.read(inputFile);
|
|
// 计算目标图片的尺寸
|
long targetSizeBytes = targetSizeKB * 1024;
|
long originalSizeBytes = getImageSize(image);
|
double compressionRatio = (double) targetSizeBytes / originalSizeBytes;
|
int targetWidth = (int) (image.getWidth() * Math.sqrt(compressionRatio));
|
int targetHeight = (int) (image.getHeight() * Math.sqrt(compressionRatio));
|
|
// 使用ImageIO进行压缩
|
BufferedImage compressedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
|
Graphics2D graphics = compressedImage.createGraphics();
|
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null);
|
graphics.dispose();
|
|
// 将压缩后的图片写入输出文件
|
File outputFile = new File(inputFile.getParent(), "compressed_" + inputFile.getName());
|
ImageIO.write(compressedImage, "jpeg", outputFile);
|
return outputFile;
|
}
|
|
public static long getImageSize(BufferedImage image) {
|
File tempFile;
|
try {
|
tempFile = File.createTempFile("temp", ".tmp");
|
ImageIO.write(image, "jpg", tempFile);
|
long size = tempFile.length();
|
tempFile.delete();
|
return size;
|
} catch (IOException ex) {
|
ex.printStackTrace();
|
return 0;
|
}
|
}
|
}
|