package com.ruoyi.service.asyn;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
public class PicUtils {
//以下是常量,按照阿里代码开发规范,不允许代码中出现魔法值
private static final Logger logger = LoggerFactory.getLogger(PicUtils.class);
private static final Integer ZERO = 0;
private static final Integer ONE_ZERO_TWO_FOUR = 1024;
private static final Integer NINE_ZERO_ZERO = 900;
private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
private static final Double ZERO_EIGHT_FIVE = 0.85;
private static final Double ZERO_SIX = 0.6;
private static final Double ZERO_FOUR_FOUR = 0.44;
private static final Double ZERO_FOUR = 0.4;
public static void imageYs(String path,int targetSizeKB) {
try {
// int targetSizeKB = 500; // 目标压缩大小(KB)
BufferedImage image = ImageIO.read(new File(path));
Image compressedImage = compressImage(image, targetSizeKB);
ImageIO.write((BufferedImage) compressedImage, "jpg", new File(path));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static Image compressImage(BufferedImage image, int targetSizeKB) {
// 计算目标图片的尺寸
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);
compressedImage.getGraphics().drawImage(image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
return compressedImage;
}
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;
}
}
}
PicUtils.imageYs(filePath,500);
直接调用