利用compressorjs压缩、纠正方向、上传图片的案例。

背景

最近要用到头像压缩和调整方向,对比了很多插件,最终选择了这款。这里分享如何使用。
https://mp.csdn.net/mdeditor/97372181#

git hub地址

https://github.com/fengyuanchen/compressorjs/blob/master/README.md#options
效果演示

学习建议

理解图片压缩,预览,上传的基本过程,对使用插件很有帮助。

demo

.fileInput{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0;
    display: block;
    width: 3.5rem;
    height: 3.5rem;
    clear: both;
    display: block;
    margin: auto;
    background-color: red;
}
  <div class="aui-info">
        <img src="imgs/txbk.png" id="img-txz" style="width: 3rem;height: 3rem" class="aui-img-round user-img"/>
        <input type="file" accept="image/*" id="file-txz" name="file" onchange="upload('#file-txz', '#img-txz');"  class="fileInput"  value="" />
    </div>

javascript
点击上传按钮时,触发upload,这个每家写法都不一样。我这里也不是最好的。

var upload = function (c, d) {
    "use strict";
    var $c = document.querySelector(c),
        $d = document.querySelector(d),
        file = $c.files[0];
    if (!file) {
        return;
    }
    new Compressor(file, {
        quality: 0.6,
        maxWidth:300,
        maxHeight:300,
        success(result) {
            blog=result;
            var reader = new FileReader();
            reader.readAsDataURL(result);
            reader.onload = function (e) {
                $d.setAttribute("src", e.target.result);
            };
        },
        error(err) {
            console.log(err.message);
        },
    });
};

过程

  1. 点击file按钮获取到上传的blog文件数组。如果是null,就结束。
  2. new Compressor 传入file的对象,指定参数,获得压缩后的file对象,这里是result。

自定义操作:
1,readAsDataURL,把压缩后的文件对象抓换为base64,$d.setAttribute(“src”, e.target.result);设置img对象的src地址,实现了预览功能。
2, blog=result; 这里我把压缩后的file传递给了blog变量,这个变量随后被我append到formdata中,用来上传文件。

参数详解

有些参数是默认的,所以我没设定。但很重要。
- strict: true, 严格的语法模式
- checkOrientation: true, 检查图片的方向
- quality: 0.8, 默认压缩质量
- maxWidth:300, maxHeight:300, 我觉得头像没必要超过300px
- convertSize: 5000000, png图片如果超过了这个数值,被转换成JPEGs。

最常用的就是上面几个,其他大家可以自己研究一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值