首先引入依赖
<!--图片压缩-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
处理代码:
package com.aaaaaa.utils;
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.FileOutputStream;
import java.io.IOException;
/**
* @author Klay
* @date 2022/2/18
*/
public class UpateImage {
private static Logger logger = LoggerFactory.getLogger(UpateImage.class);
public static void main(String[] args) throws IOException {
String filePath = "E:\\picture\\";
//修改图片大小(360*360)
String srcPath = filePath + "a.jpg";
//修改尺寸后图片名称
String newPicName = "b.jpg";
String destPath = filePath + newPicName;
boolean forceSize = true;
resizeImage(srcPath, destPath, 360, 360, forceSize);
}
/**
* 重新生成图片宽、高
*
* @param srcPath 图片路径
* @param destPath 新生成的图片路径
* @param newWith 新的宽度
* @param newHeight 新的高度
* @param forceSize 是否强制使用指定宽、高,false:会保持原图片宽高比例约束
* @return
* @throws IOException
*/
public static void resizeImage(String srcPath, String destPath, int newWith, int newHeight, boolean forceSize) throws IOException {
try {
if (forceSize) {
Thumbnails.of(srcPath).forceSize(newWith, newHeight).toFile(destPath);
} else {
Thumbnails.of(srcPath).width(newWith).height(newHeight).toFile(destPath);
}
logger.info("图片修改成功!");
} catch (Exception e) {
logger.error("图片修改尺寸失败:{}", e);
}
}
}