spring-boot图片压缩

图片压缩java的工具 thumbnailator

一、maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>atlogging</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>atlogging</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <!--图片压缩-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.35</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、控制器TestThumbnails.java

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.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping(path = "/thumb", produces = "application/json;charset=UTF-8")
public class TestThumbnails {
    /**
     * @Description:保存图片并且生成缩略图
     * @param imageFile 图片文件
     * @param request 请求对象
     * @param uploadPath 上传目录
     * @return
     */
    private static Logger log = LoggerFactory.getLogger(TestThumbnails.class);

    @RequestMapping("/up")
    public String testThumb(MultipartFile imageFile, HttpServletRequest request) {
        String res = this.uploadFileAndCreateThumbnail(imageFile, request, "");
        return res;
    }

    public static String uploadFileAndCreateThumbnail(MultipartFile imageFile, HttpServletRequest request, String uploadPath) {

        JSONObject result = new JSONObject();
        if (imageFile == null) {
            result.put("msg","imageFile不能为空");
            return result.toJSONString();
        }

        if (imageFile.getSize() >= 10 * 1024 * 1024) {
            result.put("msg","文件不能大于10M");
            return result.toJSONString();
        }
        String uuid = UUID.randomUUID().toString();

        String fileDirectory = new SimpleDateFormat("yyyyMMdd").format(new Date());//设置日期格式

        //拼接后台文件名称
        String pathName = fileDirectory + File.separator + uuid + "."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //构建保存文件路径
        //2016-5-6 yangkang 修改上传路径为服务器上
        String realPath = "F:/temp/ys";//request.getServletContext().getRealPath("uploadPath");
        //获取服务器绝对路径 linux 服务器地址  获取当前使用的配置文件配置
        //String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
        //拼接文件路径
        String filePathName = realPath + File.separator + pathName;
        log.info("图片上传路径:" + filePathName);
        //判断文件保存是否存在
        File file = new File(filePathName);
        if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
            //创建文件
            file.getParentFile().mkdirs();
        }

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            inputStream = imageFile.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            //写出文件
            //2016-05-12 yangkang 改为增加缓存
//            IOUtils.copy(inputStream, fileOutputStream);
            byte[] buffer = new byte[2048];
            IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
            buffer = null;

        } catch (IOException e) {
            filePathName = null;
            result.put("msg","操作失败");
            return result.toJSONString();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                filePathName = null;
                result.put("msg","操作失败");
                return result.toJSONString();

            }
        }


        // String fileId = FastDFSClient.uploadFile(file, filePathName);

        /**
         * 缩略图begin
         */

        //拼接后台文件名称
        String thumbnailPathName = fileDirectory + File.separator + uuid + "small."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //added by yangkang 2016-3-30 去掉后缀中包含的.png字符串
        if (thumbnailPathName.contains(".png")) {
            thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
        }
        long size = imageFile.getSize();
        double scale = 1.0d;
        if (size >= 200 * 1024) {
            if (size > 0) {
                scale = (200 * 1024f) / size;
            }
        }

        //拼接文件路径
        String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
        try {
            //added by chenshun 2016-3-22 注释掉之前长宽的方式,改用大小
//            Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
            if (size < 200 * 1024) {
                Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
            } else {
                Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
            }

        } catch (Exception e1) {
            result.put("msg", "操作失败");
            return result.toJSONString();
        }
        /**
         * 缩略图end
         */

        //原图地址
        result.put("originalUrl", pathName);
        //缩略图地址
        result.put("thumbnailUrl", thumbnailPathName);
        //缩略图地址
        result.put("msg", "操作成功");
        result.put("status", 200);
        return result.toJSONString();
    }
}
原文地址:https://www.cnblogs.com/zhizou/p/11120858.html