知识改变命运! SpringBoot系列13-整合thumbnailator将图片文件压缩转换成base64字符串_猿份哥-lskyf博客社区

SpringBoot系列13-整合thumbnailator将图片文件压缩转换成base64字符串

猿份哥 1年前 ⋅ 4319 阅读 ⋅ 0 个赞

一.Thumbnails用法介绍:

1.按指定大小把图片进行缩和放(会遵循原图高宽比例)

//此处把图片压成400×500的缩略图
//变为400*300,遵循原图比例缩或放到400*某个高度
Thumbnails.of(fromPic).size(400,500).toFile(toPic);

//按照比例进行缩小和放大
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小

Thumbnails.of(fromPic).scale(2f);//按比例放大

//不按比例,就按指定的大小进行缩放
Thumbnails.of(fromPic).size(100, 100).keepAspectRatio(false).toFile(toPic);
//或者
Thumbnails.of(fromPic).forceSize(100,100).toFile(toPic);

2.旋转图片

rotate(角度),正数则为顺时针,负数则为逆时针

Thumbnails.of(fromPic).size(200,200).rotate(90).toFile(toPic);

3.图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量

Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

4.给图片加水印,watermark(位置,水印图,透明度)Positions.CENTER表示加在中间

Thumbnails.of(fromPic).size(400,400)
        .watermark(Positions.CENTER,ImageIO.read(waterPic),0.5f)
        .outputQuality(0.8f).toFile(toPic);

5.用sourceRegion()实现图片裁剪

//图片中心300*300的区域,Positions.CENTER表示中心,还有许多其他位置可选
Thumbnails.of(fromPic).sourceRegion(Positions.CENTER,300,300)
        .size(300,300).toFile(toPic);
//图片中上区域300*300的区域
Thumbnails.of(fromPic).sourceRegion(Positions.TOP_CENTER,300,300)
        .size(300,300).toFile(toPic);
Thumbnails.of(fromPic).sourceRegion(0,0,200,200)
        .size(300,300).toFile(toPic);

以上资料摘自:https://www.cnblogs.com/ryan304/p/9546670.html

二开始实操:将图片文件使用Thumbnails图片压缩处理后转换为base64字符串

1.添加maven依赖:

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

编写工具类

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/04 18:37
 */
public class ImageUtils {

    private static String ImageFormat="jpg";


    /**
     * 按照比例和规格压缩图片得到base64图片字符串
     * @param maxSize 单位kb
     * @param w
     * @param h
     * @return
     */
    public static String resizeImage(String filePath,int maxSize,int w,int h){
        try {
            BufferedImage src = fileToBufferedImage(filePath);
            BufferedImage output = Thumbnails.of(src).size(w, h).asBufferedImage();
            String base64 = imageToBase64(output);
            while (base64.length() - base64.length() / 8 * 2 > maxSize*1000) {
                output = Thumbnails.of(output).scale(0.9f).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return imageToBase64(output);
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }


    /**
     * 图片文件转BufferedImage
     * @param filePath
     * @return
     * @throws Exception
     */
    public static BufferedImage fileToBufferedImage(String filePath) throws Exception{
        FileInputStream is=new FileInputStream(filePath);
        BufferedImage img = ImageIO.read(is);
        return  img;
    }

    /**
     * 将图片base64字符串转换为BufferedImage
     * @param base64string
     * @return
     */
    public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {
            InputStream stream = base64StringToInputStream(base64string);
            image = ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 将base64字符转换为输入流
     * @param base64string
     * @return
     */
    private static InputStream base64StringToInputStream(String base64string) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64string.getBytes());
        InputStream inputStream=byteArrayInputStream;
        return inputStream;
    }

    /**
     * 将BufferedImage转换为base64字符串
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, ImageFormat, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

}

resizeImage方法使用while循环将图片大小于压缩到指定的大小后不再压缩。

编写测试类

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/04 16:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ImageTest {

	@Test
	public void imageFileToBase64() throws Exception {
		String filePath="D:\\data\\test\\0.jpg";
		String imageStr = ImageUtils.resizeImage(filePath, 60, 300, 420);
		System.out.println(imageStr);
	}
	
}

最后猿份哥双手给大家奉上代码地址,希望大家喜欢

https://github.com/tiankonglanlande/springboot/tree/master/springboot-thumbnailator-base64


全部评论: 0

    我有话说:

    SpringBoot系列10-文件上传

    文章目录 1.先来最简单的 2.设置文件大小,请求大小 3.多文件上传 怎样使用最简单的方式上传文件,如何上传多个文件呢 先来最简单的 pom.xml文件引入依赖文件 <

    Spring Boot系列8-使用jasypt加密配置文件内容简单版

    文章目录 1.为什么配置文件需要加密 2.首先引入pom依赖文件 3.在application.properties或者application.yml文件中配置加密密码 4.获取加密内容例如:我想

    SpringBoot系列16-Spring boot2x快速整合swagger2(Open Api3注解版)

    前言:为什么要使用swagger 传统的web开发,前端和后端的HTTP接口文档交互都是使用word文档记录,存在不仅限于这些问题;不能时时更新,不易于传输etc. swagger2可以使用配置文件

    SpringBoot系列9-使用jasypt自定义stater运行时动态传入加密密码

    文章目录 1.新建springboot-encryption-configuration项目实现stater 2.pom文件引入jasypt 3.在resources/support/下配置

    Spring Boot系列1-helloword

      使用springboot简单轻松创建helloword SpringBoot系列1-helloword 关于springboot这是摘自官方的一段话 Spring Boot

    Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler

    介绍在SpringBoot中集成mybatis和druid以及自定义TypeHandler 创建数据库表 SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- --------------------...

    Spring Boot系列6-SpringBoot中使用servlet

    介绍在SpringBoot中如何使用servlet pom.xml <dependency> <groupId>org.springframework.boot<

    Spring Boot系列5-定时任务-springboot整合quartz实现动态定时任务

    MyJob实现Job接口,重写execute方法在里面操作我们要执行的业务逻辑。 @Slf4j public class MyJob implements Job { @Autowired private MyService myService;...

    SpringBoot系列15-mysql-multiple-data-sources1

    springboot 多数据源的一个简单示例 多数据源分包加载 新建数据库test1和表tbl_user CREATE TABLE `tbl_user` ( `id` int(11) NOT

    SpringBoot系列14-加载yml,properties配置文件信息

    yml前置知识 yml语法: 单个key value 写法 k:空格v eg: color: blue 对象写法 k: {k1: v1,k2: v2} k: k1: v1 k2: v2 list集合写法 k: [v1,v2,v3] k: -...

    SpringBoot系列12-redis-pipeline keys模糊查询替代方案

    keys模糊查询遇到性能问题redis cup 99%以及解决方案 之前写过一篇文章 《java redis通过key模糊删除,批量删除,批量查询相关数据》,在项目中我也是这样使用的。刚开始还没有

    Spring Boot系列2-全局统一异常处理

    原创: 天空和唯美 天空唯美  点击查看原文 为什么要全局统一异常处理呢?如果系统发生了异常,不做统一异常处理,前端会给用户展示一大片看不懂的文字。做统一异常处理后当

    spring boot系列4-定时任务-springboot自带的scheduled超级简单

    需求:创建一个每天凌晨0点执行的定时任务1.创建任务 /** * @author 天空蓝蓝的 */ @Slf4j @EnableScheduling @Component public class MyTask { @Async @Schedul...

    springboot项目运行在docker中 file.exists()返回false没有报错

      springboot项目运行在docker中 file.exists()返回false没有报错   表现:在windows运行正确,但是打包后运行在docker容器中找不到

    加入公众号
    加入公众号