Java使用Thumbnails进行文件压缩

Java使用Thumbnails进行文件压缩

前言

Thumbnails是一个图片处理库,它可以对图片进行压缩、裁剪、缩放等操作。在进行文件压缩时,可以使用Thumbnails来压缩图片文件。

所需依赖

	<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-mock</artifactId>
	    <version>2.0.8</version>
	    <scope>compile</scope>
	</dependency>

	<!-- 文件压缩 -->
    <dependency>
        <groupId>net.coobird</groupId>
        <artifactId>thumbnailator</artifactId>
        <version>0.4.18</version>
    </dependency>

主要代码


	/**
     * 文件压缩--得到File
     * @param tempPath 临时文件目录
     * @param multipartFile 要压缩的文件
     * @param width 压缩后的宽
     * @param height 压缩后的高
     * @return java.io.File
     */
    public static File compressFile(String tempPath, MultipartFile multipartFile, int width, int height) throws IOException {
        //确保此路径下有 temp.jpg文件
        File file = new File(tempPath+"/temp.jpg");
        Thumbnails.of(multipartFile.getInputStream()).size(width,height).toFile(file);
        return file;
    }

    /**
     *
     * 文件压缩--转成MultipartFile
     * @param tempPath 临时文件目录
     * @param multipartFile 要压缩的文件
     * @param width 压缩后的宽
     * @param height 压缩后的高
     * @return org.springframework.web.multipart.MultipartFile
     */
    public static MultipartFile compressMultipart(String tempPath, MultipartFile multipartFile, int width, int height) throws IOException {
        File file = compressFile(tempPath,multipartFile,width,height);
        FileInputStream input = new FileInputStream(file);
        return new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
    }

是不是很简单0.0
好了,到这就结束啦!!!

----------------------------------------------------------------------------THANKS !!!-----------------------------------------------------------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值