JavaScript 客户端图片压缩

此文章发布于 60 个月前,部分信息可能已经过时,请自行斟酌确认。

客户端拍照或选择图库中已有图片上传这个需求非常常见,一般拍照后图片都比较大,我们希望在上传之前先进行压缩到需要的尺寸,即节省了用户流量也可提高上传速度。

发现两个比较不错简单易用的 js 图片压缩库。

https://github.com/WangYuLue/image-conversion
https://github.com/fengyuanchen/compressorjs

这里以第 2 个 compressorjs 为例演示如何简单几步完成图片并上传。

演示代码基于 vue + axios 测试通过。

引用依赖:

npm install compressorjs --save

压缩及上传:

import axios from 'axios';
import Compressor from 'compressorjs';

...

mounted() {
    document.getElementById('file').addEventListener('change', (e) => {
      const file = e.target.files[0];

      if (!file) {
        return;
      }

      new Compressor(file, {
        quality: 0.6,
        success(result) {
          const formData = new FormData();

          // The third parameter is required for server
          formData.append('file', result, result.name);

          // Send the compressed image file to server with XMLHttpRequest.
          axios.post('/path/to/upload', formData).then(() => {
            console.log('Upload success');
          });
        },
        error(err) {
          console.log(err.message);
        },
      });
    });
}
最后修改:2019 年 05 月 21 日 04 : 27 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论