使用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 javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
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();
        int maxWidth = 1200;//压缩之后的图片最大宽度
        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());
        //构建保存文件路径
        //修改上传路径为服务器上
        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);
            //写出文件
//            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 thumbnailPathName = fileDirectory + File.separator + uuid + "small."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        if (thumbnailPathName.contains(".png")) {
            thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
        }
        long size = imageFile.getSize();

        double scale = 1d;
        double quality = 1d;
        if (size >= 200 * 1024) {//当图片超过200kb的时候进行压缩处理
            if (size > 0) {
                quality = (200 * 1024f) / size;
            }
        }

        //图片信息
        double width = 0;
        double height = 0;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile.getInputStream()); //获取图片流
            if (bufferedImage == null) {
                // 证明上传的文件不是图片,获取图片流失败,不进行下面的操作
            }
            width = bufferedImage.getWidth(); // 通过图片流获取图片宽度
            height = bufferedImage.getHeight(); // 通过图片流获取图片高度
            // 省略逻辑判断
        } catch (Exception e) {
            // 省略异常操作
        }
        System.out.println(width);
        while (width * scale > maxWidth) {//处理图片像素宽度(当像素大于1200时进行图片等比缩放宽度)
            scale -= 0.1;
        }

        //拼接文件路径
        String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
        System.out.println(scale);
        System.out.println(quality);
        System.out.println((int) width * scale);
        /*if(true){
            return result.toJSONString();
        }*/
        try {
            //注释掉之前长宽的方式,改用大小
//          Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
            if (size < 200 * 1024) {
                Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
            } else {
                Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);//(thumbnailFilePathName + "l.");
            }

        } 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/11244015.html