springboot整合thumbnailator实现图片压缩

前言

最近由于首页产品列表图片显示太慢,经过研究发现是用户上传的图片太大。

针对这个问题,想到的解决方案是:

1、 产品上传时,限定图片上传大小不超过2m

2、 上传成功后将产品图片进行压缩,但是保留原图片,压缩后的图片名称添加后缀”-thumbnail”

3、 对已经上传的产品图片全部进行压缩

4、 前端只有在点击查看产品大图时显示原图,其他情况均显示缩略图

实现

根据需求,找到的解决方法是使用net.coobird.thumbnailator依赖包,实现图片压缩和将指定目录下的图片全部压缩的功能

引入maven依赖

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

具体实现

ImageUtil类

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename; import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; /**
* 图片压缩工具类
*
* @author lnj
* createTime 2018-10-19 15:31
**/
public class ImageUtil { // 图片默认缩放比率
private static final double DEFAULT_SCALE = 0.8d; // 缩略图后缀
private static final String SUFFIX = "-thumbnail"; /**
* 生成缩略图到指定的目录
*
* @param path 目录
* @param files 要生成缩略图的文件列表
* @throws IOException
*/
public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException {
return generateThumbnail2Directory(DEFAULT_SCALE, path, files);
} /**
* 生成缩略图到指定的目录
*
* @param scale 图片缩放率
* @param pathname 缩略图保存目录
* @param files 要生成缩略图的文件列表
* @throws IOException
*/
public static List<String> generateThumbnail2Directory(double scale, String pathname, String... files) throws IOException {
Thumbnails.of(files)
// 图片缩放率,不能和size()一起使用
.scale(scale)
// 缩略图保存目录,该目录需存在,否则报错
.toFiles(new File(pathname), Rename.SUFFIX_HYPHEN_THUMBNAIL);
List<String> list = new ArrayList<>(files.length);
for (String file : files) {
list.add(appendSuffix(file, SUFFIX));
}
return list;
} /**
* 将指定目录下所有图片生成缩略图
*
* @param pathname 文件目录
*/
public static void generateDirectoryThumbnail(String pathname) throws IOException {
generateDirectoryThumbnail(pathname, DEFAULT_SCALE);
} /**
* 将指定目录下所有图片生成缩略图
*
* @param pathname 文件目录
*/
public static void generateDirectoryThumbnail(String pathname, double scale) throws IOException {
File[] files = new File(pathname).listFiles();
compressRecurse(files, pathname);
} /**
* 文件追加后缀
*
* @param fileName 原文件名
* @param suffix 文件后缀
* @return
*/
public static String appendSuffix(String fileName, String suffix) {
String newFileName = ""; int indexOfDot = fileName.lastIndexOf('.'); if (indexOfDot != -1) {
newFileName = fileName.substring(0, indexOfDot);
newFileName += suffix;
newFileName += fileName.substring(indexOfDot);
} else {
newFileName = fileName + suffix;
} return newFileName;
} private static void compressRecurse(File[] files, String pathname) throws IOException {
for (File file : files) {
// 目录
if (file.isDirectory()) {
File[] subFiles = file.listFiles();
compressRecurse(subFiles, pathname + File.separator + file.getName());
} else {
// 文件包含压缩文件后缀或非图片格式,则不再压缩
String extension = getFileExtention(file.getName());
if (!file.getName().contains(SUFFIX) && isImage(extension)) {
generateThumbnail2Directory(pathname, file.getAbsolutePath());
}
}
}
} /**
* 根据文件扩展名判断文件是否图片格式
*
* @param extension 文件扩展名
* @return
*/
public static boolean isImage(String extension) {
String[] imageExtension = new String[]{"jpeg", "jpg", "gif", "bmp", "png"}; for (String e : imageExtension) if (extension.toLowerCase().equals(e)) return true; return false;
} public static String getFileExtention(String fileName) {
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
return extension;
}
}

测试

import org.junit.Test;

import java.io.IOException;
import java.util.List; /**
* @author lnj
* createTime 2018-10-19 15:39
**/
public class ImageUtilTest { /**
* 测试在指定目录下生成缩略图
*/
@Test
public void testGenerateThumbnail2Directory() throws IOException {
String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image";
String[] files = new String[]{
"image/1.jpg",
"image/2.jpg"
}; List<String> list = ImageUtil.generateThumbnail2Directory(path, files);
System.out.println(list);
} /**
* 将指定目录下的图片生成缩略图
*/
@Test
public void testGenerateDirectoryThumbnail() throws IOException {
String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image";
ImageUtil.generateDirectoryThumbnail(path);
}
}

代码下载地址

https://github.com/linj6/springboot-learn/tree/master/springboot-thumbnail

参考资料

https://juejin.im/post/5b138045f265da6e603934ab#comment
 

springboot整合thumbnailator实现图片压缩的更多相关文章

  1. springboot整合ueditor实现图片上传和文件上传功能

    springboot整合ueditor实现图片上传和文件上传功能 写在前面: 在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作: springboot+layui 整合百度富文本 ...

  2. Thumbnailator java图片压缩,加水印,批量生成缩略图

    地址:http://code.google.com/p/thumbnailator/ 1.指定大小进行缩放 //size(宽度, 高度) /* * 若图片横比200小,高比300小,不变 * 若图片横 ...

  3. SpringBoot整合FastDFS实现图片的上传

     文件的上传和预览在web开发领域是随处可见,存储的方式有很多,本文采用阿里巴巴余庆大神开发的FastDFS进行文件的存储,FastDFS是一个分布式文件存储系统,可以看我上一篇博文,有安装和配置教程 ...

  4. Java使用google开源工具Thumbnailator实现图片压缩

    <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</ar ...

  5. 玩转 SpringBoot2.x 之整合 thumbnailator 图片处理

    1.序 在实际项目中,有时为了响应速度,难免会对一些高清图片进行一些处理,比如图片压缩之类的,而其中压缩可能就是最为常见的.最近,阿淼就被要求实现这个功能,原因是客户那边嫌速度过慢.借此机会,阿淼今儿 ...

  6. 四:Java使用google的thumbnailator工具对图片压缩水印等做处理

    Thumbnailator是一个非常好的图片开源工具 使用方法: 在pom中加入以下jar包 <!-- 图片缩略图 图片压缩 水印 start--> <dependency>& ...

  7. 分布式文件系统FastDFS简介、搭建、与SpringBoot整合实现图片上传

    之前大学时搭建过一个FastDFS的图片服务器,当时只是抱着好奇的态度搭着玩一下,当时搭建采用了一台虚拟机,tracker和storage服务在一台机器上放着,最近翻之前的博客突然想着在两台机器上搭建 ...

  8. 很详细的SpringBoot整合UEditor教程

    很详细的SpringBoot整合UEditor教程 2017年04月10日 20:27:21 小宝2333 阅读数:21529    版权声明:本文为博主原创文章,未经博主允许不得转载. https: ...

  9. Java后端实现图片压缩技术

    今天来说说图片压缩技术,为什么要使用图片压缩,图片上传不就完事了吗?对的,这在几年前可以这么说,因为几年前还没有现在这么大的并发,也没有现在这么关注性能. 如今手机很多,很多人都是通过手机访问网络或者 ...

随机推荐

  1. Centos配置深度学习开发环境

    目录 1. 安装显卡驱动 2. 安装CUDA\CUDNN 3. 安装TensorFlow-gpu 测试 1. 安装显卡驱动 检测显卡驱动及型号 $ sudo rpm --import https:// ...

  2. Dictionary tabPage使用

    public override bool AccptChange() { //if (oldvalue == null || oldvalue.Count <= 0) //{ // return ...

  3. HTML5+Bootstrap 学习笔记 1

    HTML <header> 标签 <header> 标签定义文档的页眉(介绍信息),是 HTML 5 中的新标签. 参考资料: HTML <header> 标签 h ...

  4. 【转】Linux内核结构详解

    Linux内核主要由五个子系统组成:进程调度,内存管理,虚拟文件系统,网络接口,进程间通信. 1.进程调度 (SCHED):控制进程对CPU的访问.当需要选择下一个进程运行时,由调度程序选择最值得运行 ...

  5. 20170413B端业务访问故障排查思路

    现象: 1.全国用户电视端页面无法显示,刷不出版面. 2.后端服务无法打开,报错,504,502   显示服务器端业务故障超时. 3.其他业务也出现缓慢情况,并不严重. 排查: 1.系统服务排查,常规 ...

  6. angularJS遇到的坑

    最近在用angularjs做一些东西,由于学艺不精,对angularjs了解不够,导致经常会不小心掉进一些自己挖的坑里(⊙_⊙),在这里记下来,谨防又踩. 1.angularjs ng-show no ...

  7. 活学活用wxPython

    http://www.czug.org/python/wxpythoninaction/

  8. Agile.Net 组件式开发平台 - 服务开发示例

    在上一篇文章中已经讲解了组件的开发,这篇文章讲解平台服务开发. Agile.Net开发管理平台项目,已经托管在开源中国码云平台(http://git.oschina.net) 登陆码云平台进入项目主页 ...

  9. 【SQLAlchemy】SQLAlchemy技术文档(中文版)(上)

    1.版本检查 import sqlalchemy sqlalchemy.__version__ 2.连接 from sqlalchemy import create_engine engine = c ...

  10. 【codevs3160】最长公共子串 后缀数组

    题目描述 给出两个由小写字母组成的字符串,求它们的最长公共子串的长度. 输入 读入两个字符串 输出 输出最长公共子串的长度 样例输入 yeshowmuchiloveyoumydearmotherrea ...