Bootstrap

使用Thumbnails工具对图片进行缩放,压缩

Thumbnails是Google公司开源的图片处理工具

一、将Thumbnails引入到maven工程

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

二、关键代码

String filePathName = "需要压缩的图片根路径";
String thumbnailFilePathName = "压缩之后的图片路径";
double scale = 1d;//图片缩小倍数(0~1),1代表保持原有的大小
double quality = 1d;//压缩的质量,1代表保持原有的大小(默认1)

Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);

Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);

Thumbnails.of(filePathName).size(400,500).toFile(thumbnailFilePathName);//变为400*500,遵循原图比例缩或放到400*某个高度

三、Spring-boot的例子

package com.example.atlogging.controller;

import com.alibaba.fastjson.JSONObject;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import
;