1.pom.xml引入依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
2.接口
/**
* 上传人员头像
* @param multipartFile
* @return
*/
@Log(title = "人员头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
@SneakyThrows
public AjaxResult avatar(@RequestParam("multipartFile") MultipartFile multipartFile){
if (!multipartFile.isEmpty()){
String fileName = FileUploadUtils.extractFilename(multipartFile);
byte[] bytes = multipartFile.getBytes();
bytes = ThumbnailUtis.compressPictureForScale(bytes,92,128);
//将字节数组写入到文件
String filePath= RuoYiConfig.getAvatarPath()+"/"+fileName;
FileUtils.writeByteArrayToFile(new File(filePath),bytes);
//上传压缩后的图片
//String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
String url=FileUploadUtils.getPathFileName(RuoYiConfig.getAvatarPath(),fileName);
log.info("url={}",url);
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
return ajax;
}
return AjaxResult.error("上传头像异常,请联系管理员");
}
3.工具类
/**
* 文件压缩处理类
*
* @author xiaoss
* @since 1.0, 2022年05月26日 17:32:12
*/
@Slf4j
public class ThumbnailUtis {
/**
* 根据指定尺寸压缩图片
*
* @param imageBytes 源图片字节数组
* @param width
* @param hight
* @return 压缩质量后的图片字节数组
*/
@SneakyThrows
public static byte[] compressPictureForScale(byte[] imageBytes,int width,int hight) {
if (imageBytes == null || imageBytes.length <= 0) {
return imageBytes;
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream).size(width,hight).keepAspectRatio(false).toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
return imageBytes;
}
}