public Resp addImage(MultipartFile file) {
//获取项目classess/static的地址
String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
Map<String, String> imgInfo = new HashMap<String, String>();
if (file != null) {
//获取图片的名称
String oldName = file.getOriginalFilename();
//随机生成数字来作为图片的前缀加上图片的格式jpg/png
String newName = randomNum() + oldName.substring(oldName.lastIndexOf("."));
//图片保存路径
String savePath = staticPath + File.separator + "imgGallery";
File folder = new File(savePath);
//没有文件夹imgGallery就创建
if (!folder.exists()) {
folder.mkdirs();
}
try {
//压缩图片再保存outputQuality(1f) 越接近1,图片质量越高
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(1f).outputFormat("jpg").toFile(new File(folder,newName));
//直接保存
//file.transferTo(new File(folder, newName));
//获取保存的图片
String imgUrl = ResourceUtils.getURL("classpath:").getPath() + "static/imgGallery/" + newName;
imgInfo.put("imgUrl", imgUrl);
} catch (IOException e) {
e.printStackTrace();
}
return Resp.ok("上传成功").put("imgInfo", imgInfo);
}
return Resp.error("上传失败");
}
springboot上传图片并且压缩到项目资源目录下
最新推荐文章于 2024-07-06 13:45:00 发布