<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
public static boolean saveFileByMultipartFile(String directoryPath, String fileName, MultipartFile multipartFile) {
try {
if (StringUtils.isEmpty(directoryPath)) {
throw new Exception("文件夾不能爲空");
}
File tmp = new File(directoryPath);
if (!tmp.exists()) {
tmp.mkdirs();
}
String filePath = directoryPath + fileName;
multipartFile.transferTo(new File(filePath));
String fileType = multipartFile.getContentType();
if (!StringUtils.isEmpty(fileType) && fileType.contains("image")) {
// File file = new File(filePath);
// log.error("壓縮前圖片大小:Byte:" + file.length());
// 壓縮代碼
//防止圖片變紅
Image src = Toolkit.getDefaultToolkit().getImage(filePath);
BufferedImage image = toBufferedImage(src);
Thumbnails.of(image).scale(1f).toFile(filePath);
// log.error("壓縮前圖片大小:Byte:" + file.length());
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
我測試過 可以解決