没想到,几行代码,你就可以实现图片压缩(springboot)!

时间:2022-07-22
本文章向大家介绍没想到,几行代码,你就可以实现图片压缩(springboot)!,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

啊啊啊,一些工作上遇到的一些问题,记录下来,方便以后查看吧,也希望能帮助到大家,所以就打算归类到springboot 番外篇了。

好了,废话不多说,最近要做一个功能,客户端上传图片到服务端,再从服务端通过文件名下载文件。其实最好的静态文件最好还是通过nginx 获取比较快,但是由于想要做一个缩略图的效果,其实缩略图在前端也可以做,但是任务安排下来了那就做吧。

也考虑在上传文件的时候如果是图片就生成一个缩略图,但是这个功能之前上线过一次,之前有的图片就没有很好的办法生成缩略图了,所以就成了在下载的时候来生成缩略图。实现方案如下:

引入依赖

在pom.xml 文件中引入如下依赖:

  <!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

ImageUtil

我们创建一个 ImageUtil 工具类。内容如下:

public class ImageUtil {
    /**
     * 按尺寸原比例缩放图片
     * @param source 输入源
     * @param output 输出源
     * @param width 256
     * @param height 256
     * @throws IOException
     */
    public static void imgThumb(String source, String output, int width, int height) throws IOException {
        Thumbnails.of(source).size(width, height).toFile(output);
    }
    
    /**
     * 按照比例进行缩放
     * @param source 输入源
     * @param output 输出源
     * @param scale  比例
     * @throws IOException
     */
    public static void imgScale(String source, String output, double scale) throws IOException {
        Thumbnails.of(source).scale(scale).toFile(output);
    }
}

主要就是使用到Thumbnails 实现按像素压缩和按比例压缩,这两种方法都是缩略后保持原比例的不会失真变形的,算是比较常用的了,当然 Thumbnails 还有其他的功能,感兴趣的可以搜索学习一下。

下载的接口

创建一个DownloadFileConfig 类,内容如下:

@RestController
@RequestMapping("/config")
public class DownloadFileConfig {

    private static final Logger log = LoggerFactory.getLogger(DateUtils.class);

    private static final String WEBAPPPATH = PathUtil.getRootPath() + ConstantPool.ANNEX;


    @RequestMapping("/download")
    public String fileDownLoad(HttpServletResponse response, @RequestParam("annexName") String annexName, @RequestParam("type") String type){

        String totalUrl = WEBAPPPATH +annexName;
        String output=totalUrl;
        String fileName=annexName;
        if(type.equals(ConstantPool.THUMBNAIL) &&
                (annexName.contains(ConstantPool.SEPARATORBMP)
                        || annexName.contains(ConstantPool.SEPARATORGIF)
                        || annexName.contains(ConstantPool.SEPARATORPNG)
                        || annexName.contains(ConstantPool.SEPARATORJPEG)
                        || annexName.contains(ConstantPool.SEPARATORJPG)
                        || annexName.contains(ConstantPool.SEPARATORWEBP))
                ){
            int index=annexName.lastIndexOf(ConstantPool.SEPARATORPOINT);
            fileName=annexName.substring(0,index)+type+annexName.substring(index);
            output=WEBAPPPATH+fileName;
            try {
                ImageUtil.imgThumb(totalUrl,output,ConstantPool.WIDTH,ConstantPool.HEIGHT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int index=fileName.indexOf(ConstantPool.SEPARATORSLASH);
        String downloadFileName =fileName.substring(index+1);
        log.info(output);
        File file = new File(output);
        if(!file.exists()){
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename="+downloadFileName );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }

}

这里用到常量池,ConstantPool内容如下:

public class ConstantPool {

    private ConstantPool(){
    }

    public static final  String SEPARATORNULL ="";
    public static final  String SEPARATORPOINT =".";
    public static final   String SEPARATORSLASH ="/";
    public static final   String SEPARATORJPG =".jpg";
    public static final   String SEPARATORJPEG =".jpeg";
    public static final   String SEPARATORBMP =".bmp";
    public static final   String SEPARATORPNG =".png";
    public static final   String SEPARATORGIF =".gif";
    public static final   String SEPARATORWEBP =".webp";
    public static final   String THUMBNAIL ="缩略图";
    public static final   int WIDTH =256;
    public static final   int HEIGHT =256;
}

上面的下载接口,整个逻辑也很简单,就是先判断type 传的是否是缩略图,如果是则表示是要缩略的图片,则对图片进行压缩后输出,否则就直接输出文件。整个就搞定啦~

测试效果

我们在写测试效果的html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <img data-v-8ecfafb6="" src="http://127.0.0.1:9015/sdrwkb/config/download.mt?annexName=1578444949941/HRZhao头像.png&type=缩略图" alt="img">
    <img data-v-8ecfafb6="" src="http://127.0.0.1:9015/sdrwkb/config/download.mt?annexName=1578444949941/HRZhao头像.png&type=" alt="img">
    
</body>
</html>

效果如下: