java对图片按照指定尺寸压缩

44 篇文章 0 订阅
20 篇文章 0 订阅

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;
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值