java使用Thumbnailator实现图片压缩

随着现在的手机像素越来越高,生成的照片越来越大,图片上传服务器后加载就会比较缓慢,可以通过上传图片压缩的方式缩小图片大小。而用到的就是Google开源工具Thumbnailator。
1.添加jar包

<!-- Thumbnailator 图片压缩 -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

2.常用方法

// 原图文件路径
Thumbnails.of(file.getInputStream())
        .scale(1f) // 值在0到1之间,1f就是原图大小,0.5就是原图的一半大小
        .outputQuality(0.1f) // 值也是在0到1,越接近于1质量越好,越接近于0质量越差
        .toFile(img); // 压缩后文件的路径

3.其他用法

1.指定大小比例进行缩放--考虑图片的完整度
  size(宽度, 高度)
2.按照比例进行缩放
  scale(比例)
3.不按照比例,指定大小进行缩放--不考虑图片的完整度
  size(宽度, 高度).keepAspectRatio(false)
4.图片旋转
  size(宽度, 高度).rotae(90) -- 旋转90(必须加size不然报错)
5.水印
  BOTTOM_RIGHT 右下角
  CENTER       中心
  size(宽度, 高度).watermark(Positions.CENTER,)
      .size(1280, 1024)
      .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("d:/uploadImg/head.png")), 0.5f)
      .outputQuality(0.8f)
      .toFile(dest);
6.裁剪 -- 以图片中心400*400区域
  .sourceRegion(Positions.CENTER, 400,400)
  .size(200,200).keepAspectRatio(false)
7.转化图像格式
  .size(200,200).outputFormat(".png")

4.工具类

/**
 * 图片上传压缩
 *
 * @param file 文件
 * @param subdirectory 文件夹名称
 * @param width 图片宽度
 * @param height 图片高度
 * @return
 */
public static Map<String, String> saveImgCompress(MultipartFile file, String subdirectory,Integer width,Integer height) {
    
    
    //上传文件路径
    String path = GetServerPathUtil.getPath("uploadImg");
    // 获取文件名称
    String filename = file.getOriginalFilename();
    String fielhouzhui = filename.substring(filename.lastIndexOf("."), filename.length());
    //重新修改文件名防止重名
    filename = new SimpleDateFormat("yyyyMMddHHmmssSSS")
            .format(new Date())
            + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + StringUtils.getUUID() + fielhouzhui;
    File filepath = new File(path, filename);
    //判断路径是否存在,没有就创建一个
    if (!filepath.getParentFile().exists()) {
    
    
        filepath.getParentFile().mkdirs();
    }
    File img = new File(path + File.separator + filename);
    Map<String, String> map = new HashMap<>();
    try {
    
    
        Thumbnails.of(file.getInputStream()).size(width,height).toFile(img);
        map.put("res", "success");
        map.put("url", filename);
        return map;
    } catch (IOException e) {
    
    
        LOG.info(filename + "图片上传失败:" + e);
        map.put("res", "error");
        return map;
    }
}
/**
 * 获取文件目录
 *
 * @param subdirectory 文件夹名称
 * @return
 */
public static String getPath(String subdirectory) {
    
    
    //获取跟目录---与jar包同级目录的upload目录
    File upload = null;
    try {
    
    
        // 获取项目中所在的路径
        // C:\Users\Administrator\Desktop\SpringBoot\xx\xx-common\target\classes
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        // 判断目录是否存在
        if (!path.exists()) path = new File("");
        // 项目运行目录 + subdirectory
        upload = new File(path.getAbsolutePath(), subdirectory);
        //如果不存在则创建目录
        if (!upload.exists()) upload.mkdirs();
        String realPath = upload + "/";
        return realPath;// C:\Users\Administrator\Desktop\SpringBoot\XX\XX-common\target\classes\123/
    } catch (FileNotFoundException e) {
    
    
        LOG.info("GetServerPathUtil===>获取服务器路径发生错误!");
        System.err.println("GetServerPathUtil===>获取服务器路径发生错误!");
        throw new RuntimeException("获取服务器路径发生错误!");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37131111/article/details/129713602