图片压缩

This commit is contained in:
yangjun 2024-07-15 17:19:38 +08:00
parent 017c2488c4
commit 6983d37a86
1 changed files with 29 additions and 0 deletions

View File

@ -9,6 +9,7 @@ import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
@ -116,9 +117,37 @@ public class FileUploadUtils
//file.transferTo(desc);
IoUtil.close(out);
String pathFileName = getPathFileName(baseDir, fileName);
try {
File inputImageFile = new File(pathFileName); // 替换为实际图片路径
byte[] compressedImage = compressImage(inputImageFile, 0.5f); // 压缩比例如0.5表示压缩50%
// 将压缩后的图片保存到文件
File outputFile = new File(pathFileName); // 替换为输出图片路径
ImageIO.write(ImageIO.read(new ByteArrayInputStream(compressedImage)), "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
return pathFileName;
}
public static byte[] compressImage(File imageFile, float scale) throws IOException {
BufferedImage originalImage = ImageIO.read(imageFile);
// 保存缩放后的图片到输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Image compressedImage = originalImage.getScaledInstance(
(int)(originalImage.getWidth() * scale),
(int)(originalImage.getHeight() * scale),
Image.SCALE_SMOOTH);
BufferedImage outputImage = new BufferedImage(
compressedImage.getWidth(null),
compressedImage.getHeight(null),
BufferedImage.TYPE_INT_RGB);
outputImage.createGraphics().drawImage(compressedImage, 0, 0, null);
ImageIO.write(outputImage, "png", outputStream); // 或者 "png" 如果是PNG图片
return outputStream.toByteArray();
}
/**
* 编码文件名
*/