• springboot整合thumbnailator实现图片压缩


    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
     

     

  • 相关阅读:
    linux共享内存的命令
    css元素类型
    不争万年,只珍朝夕我对编程的态度
    Oracle读书笔记PL/SQL编程(二)之程序流程
    oracle读书笔记PL/SQL编程(一)之基本数据类型、程序结构
    关于解决oracle登录:ora12154:tns:无法解析指定的连接标识符
    Hibernate读书笔记hibernate第一个案例的分析
    Oracle读书笔记PL/SQL编程(三)之游标
    解决jscollpan不能出现水平滑动条的问题
    关于org.hibernate.exception.SQLGrammarException: could not insert:
  • 原文地址:https://www.cnblogs.com/zuidongfeng/p/9853335.html
Copyright © 2020-2023  润新知