图片压缩
This commit is contained in:
parent
017c2488c4
commit
6983d37a86
|
|
@ -9,6 +9,7 @@ import org.apache.commons.lang3.time.DateFormatUtils;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.awt.*;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
|
@ -116,9 +117,37 @@ public class FileUploadUtils
|
||||||
//file.transferTo(desc);
|
//file.transferTo(desc);
|
||||||
IoUtil.close(out);
|
IoUtil.close(out);
|
||||||
String pathFileName = getPathFileName(baseDir, fileName);
|
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;
|
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();
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 编码文件名
|
* 编码文件名
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue