SSm 校园商铺4-3 Thumbnailator图片处理和封装Util

Thumbnailator图片处理和封装Util

本节记录,该视频中一些主要内容。

1. 引入依赖

 <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.8</version>
    </dependency>

tip: thumbnail 缩略图 thumbnailator 缩略图器

2. Thumbnailator的简单使用

String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
   Thumbnails.of(new File("/Users/crazys/Downloads/timg.jpeg"))
                .size(200, 200)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
                .outputQuality(0.8f)
                .toFile("/Users/crazys/Downloads/timgnew.jpeg");
        }

其中basePath用于获取classpath。
of中放 要进行处理的图片,对象类型是File;
size中是生成的文件的长宽
watermark:添加水印,第一个参数添加水印的位置,第二个参数添加水印的图片,第三个参数表示透明程度
outputQuality:输出的质量,可能与图片的清晰程度有管
toFile中放生成的新文件的位置。

3. 编写工具类PathUtil

package com.imooc.o2o.util;

/***
 * @Description: ''
 * @Author: ZBZ
 * @Date: 2020/7/23
 */
public class PathUtil {
    private static String seperator = System.getProperty("file.seperator");
    /***
     * @Author: ZBZ
     * @Description: 得到文件的basePath,后面可以使用springboot来简化配置
     * @Date: 2020/7/23

     * @return: java.lang.String
     **/
    public static String getImgBasePath(){
        String os = System.getProperty("os.name");
        String basePath="";
        if(os.toLowerCase().startsWith("win")){
            basePath="D:/o2o/image/";
        }else{
            basePath = "/home/crazys/image/";
        }
        basePath=basePath.replace("/",seperator);
        return basePath;
    }

    public static String getShopImgPath(long shopId){
        String imagePath = "/upload/item/shop" + shopId + "/";
        return imagePath.replace("/",seperator);
    }
}

这个PathUtil工具类,用于对地址的处理,其中包含两个方法,getImgBasePath(),以及getShopImgPath。

seperator 用于得到系统的分隔符;
getImgBasePath(): 首先获取系统的名字,有win,mac和linux;首先将该名字转小写,然后判断是不是以win开头,若是则指定基地址,basePath;否,就代表是mac或者Linux,由于我使用的是linux,这里设定basePath="/home/crazys/image/"
然后需要对分隔符进行replace,Mac和linux为"/",windows为""。
这里的bashPath用于指定用户上传的图片所存的基地址的路径。
getShopImgPath():返回的地址为/upload/item/shop/shopId/。

4. 编写ImageUtil类,用于对图片进行处理。

public class ImageUtil {
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /***
     * @Author: ZBZ
     * @Description: 将CommonsMultipartFile转换测红File
     * @Date: 2020/7/23
     * @Param cFile:
     * @return: java.io.File
     **/
    public static File transferCommonsMutFileToFile(CommonsMultipartFile cFile){
        File newFile = new File(cFile.getOriginalFilename());
        try {
            cFile.transferTo(newFile);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return newFile;
    }

    /***
     * @Author: ZBZ
     * @Description: 处理缩略图,并返回新生成图片的相对值路径
     *
     * @Date: 2020/7/23
     * @Param thumbnail:
     * @Param targetAddr:
     * @return: java.lang.String
     **/
    public static String generateThumbnail(File thumbnail, String targetAddr) {
        String reaFileName = getRandomFileName();
        String extension = getFileExtension(thumbnail);
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + reaFileName + extension;
        logger.debug("current relativeAddr is:" + relativeAddr);
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("current complete addr is:" + PathUtil.getImgBasePath() + relativeAddr);
        try {
            Thumbnails.of(thumbnail).size(200, 200)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
                    .outputQuality(0.8f).toFile(dest);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /***
     * @Author: ZBZ
     * @Description: 创建目标路径所设计到的目录,即/home/work/crazys/xxx.jpg
     * 那么home work crazys这3个文件夹都得自动创建
     * @Date: 2020/7/23
     * @Param targetAddr:
     * @return: void
     **/
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /***
     * @Author: ZBZ
     * @Description: 获取输入文件流的扩展名
     * @Date: 2020/7/23
     * @Param thumbnail:
     * @return: java.lang.String
     **/
    private static String getFileExtension(File cFile) {
        String originalFilename = cFile.getName();
        return originalFilename.substring(originalFilename.lastIndexOf("."));

    }

    /***
     * @Author: ZBZ
     * @Description: 生成随机文件名,当前年月日小时分钟秒钟+五位随机数
     * @Date: 2020/7/23

     * @return: java.lang.String
     **/
    private static String getRandomFileName() {
        //获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr + rannum;
    }
}

这个类的主要功能是generateThumbnai():生成缩略图,然后参数传递的是
File thumbnail 和String targetAddr。
因为前端上传文件springboot封装的类为CommonsMultipartFile,这个类转为File很简单,但是File去转换为该类比较困难,因此需要新加一个方法,用于将CommonsMultipartFile转化为File类型,该方法为transferCommonsMutFileToFile。
仔细看,还是很好去理解的,就是直接不太好写出来。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值