Java uses Thumbnailator to achieve image compression

As the pixels of mobile phones are getting higher and higher, the generated photos are getting bigger and bigger, and the loading of the pictures will be slow after uploading to the server. You can reduce the size of the pictures by uploading pictures and compressing them. The Google open source tool Thumbnailator is used.
1. Add jar package

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

2. Common methods

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

3. Other usage

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. Tools

/**
 * 图片上传压缩
 *
 * @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("获取服务器路径发生错误!");
    }
}

Guess you like

Origin blog.csdn.net/qq_37131111/article/details/129713602