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

点击蓝字关注我们吧 f0004270ba4c663e61d7254237e65d9a.png

d2f9e72c447e1abe30c2b654bdd7c4db.png

前言

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

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

d70f3f03f8ab278110770a00a67420db.png

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

引入依赖

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

  
        net.coobirdthumbnailator0.4.8

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

c43203294b9f74e8a6655471bc54c998.gif

测试效果

我们在写测试效果的html

html>
"en">

    "UTF-8">
    "viewport" content="width=device-width, initial-scale=1.0">
    "X-UA-Compatible" content="ie=edge">
    Document


    "" src="http://127.0.0.1:9015/sdrwkb/config/download.mt?annexName=1578444949941/HRZhao头像.png&type=缩略图" alt="img">
    "" src="http://127.0.0.1:9015/sdrwkb/config/download.mt?annexName=1578444949941/HRZhao头像.png&type=" alt="img">
    


效果如下:8d1359a2425087132f0b2d43c78813be.png

番外

写的比较粗糙,但也比较简单,希望能帮到大家。

如果你觉得有用,记得收藏喔

378185b5ce894098ba9400054fed6bb6.png

好文!必须在看
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值