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




前言

啊啊啊,一些工做上遇到的一些问题,记录下来,方便之后查看吧,也但愿能帮助到你们,因此就打算归类到springboot 番外篇了。html

好了,废话很少说,最近要作一个功能,客户端上传图片到服务端,再从服务端经过文件名下载文件。其实最好的静态文件最好仍是经过nginx 获取比较快,可是因为想要作一个缩略图的效果,其实缩略图在前端也能够作,可是任务安排下来了那就作吧。前端

也考虑在上传文件的时候若是是图片就生成一个缩略图,可是这个功能以前上线过一次,以前有的图片就没有很好的办法生成缩略图了,因此就成了在下载的时候来生成缩略图。实现方案以下: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 工具类。内容以下:web

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 还有其余的功能,感兴趣的能够搜索学习一下。spring

下载的接口

建立一个DownloadFileConfig 类,内容以下:springboot


@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 传的是不是缩略图,若是是则表示是要缩略的图片,则对图片进行压缩后输出,不然就直接输出文件。整个就搞定啦~app

测试效果

咱们在写测试效果的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>

效果以下:

番外

写的比较粗糙,但也比较简单,但愿能帮到你们。

若是你以为有用,记得收藏喔



好文!必须在看




本文分享自微信公众号 - 程序员爱酸奶(cxyisnai)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。