使用谷歌开源的thumbnailator来限制图片大小并保存

  • 我们先来导入依赖
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>
  • 然后再来编写一个工具类
public class thumbnailator {
    /**
     * 重新生成图片宽、高
     * @param srcPath 图片路径
     * @param destPath 新生成的图片路径
     * @param newWith 新的宽度
     * @param newHeight 新的高度
     * @param forceSize 是否强制使用指定宽、高,false:会保持原图片宽高比例约束
     * @return
     * @throws IOException
     */
    public boolean resizeImage (String srcPath, String destPath, int newWith, int newHeight, boolean forceSize) throws IOException {
        if (forceSize) {
            Thumbnails.of(srcPath).forceSize(newWith, newHeight).toFile(destPath);
        } else {
            Thumbnails.of(srcPath).width(newWith).height(newHeight).toFile(destPath);
        }
        return true;
    }
}
再来编写SSM框架中使用方法
    @RequestMapping("/editinfo/{id}")
    public String editinfo(@PathVariable("id")Integer id,
                           @RequestParam("img")MultipartFile file,
                           @RequestParam("username")String username,
                           @RequestParam("motto")String motto,
                           HttpSession session){
        String path = "D:\\IDE\\IDEA_Demo\\Study_SSM08\\src\\main\\webapp\\images\\";//表示到项目的根目录下,要是想到目录下的子文件夹,修改"/"即可
        String prefilename = file.getOriginalFilename();
        if (file.getOriginalFilename().equals("")){
            userService.edituserinfo(id, username, motto);
        }else {
            String newfilename = UUID.randomUUID()+prefilename.substring(prefilename.lastIndexOf('.'));
            String resizefilename = UUID.randomUUID()+prefilename.substring(prefilename.lastIndexOf('.'));
            File newfile = new File(path+newfilename);
            try {
                file.transferTo(newfile);
                thumbnailator.resizeImage(path+newfilename,
                        path+resizefilename,
                        100,100,true);
            } catch (IOException e) {
                e.printStackTrace();
                return "redirect:/user_info.jsp";
            }
            userService.edituserinfohaveimg(id, username, motto, "images/"+resizefilename);
        }

        return "redirect:/editstate/"+id;
    }
  • 最后,来看看效果

这是原图
在这里插入图片描述
这是修改大小后效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值