input file图片上传, js 对图片尺寸进行等比例压缩处理

//file 上传图片,绑定change事件
<input type="file" onChange="uploadPic(this)" accept="image/*" />

function uploadPic(e) {
        var file = e.files[0];
        function callback(data){//回调获取压缩后的Blog
           if(data){
               console.log("压缩成功")
           }
         }
        this.compress(file, callback);
    }

//当图片宽度大于640时 进行等比例压缩,并返回Blob,否则返回false
function compress(fileObj, callback) {
        function dataURLtoBlob(dataurl) {//base64格式图片 转为Blob  
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        }
        if (typeof (FileReader) === 'undefined') {
            console.log("当前浏览器内核不支持base64图标压缩");
            return false;
        } else {
            try {
                var reader = new FileReader();
                var image = new Image();
                reader.readAsDataURL(fileObj);//开始读取指定的Blob中的内容。返回base64
                reader.onload = function (ev) {
                    image.src = ev.target.result;
                    image.onload = function () {
                        var imgWidth = this.width,
                            imgHeight = this.height; //获取图片宽高
                        if (imgWidth > 640) {//设置图片的最大宽度为640
                            imgWidth = 640;
                            imgHeight = 640 / this.width * imgHeight;//设置等比例高度
                            var canvas = document.createElement('canvas');
                            var ctx = canvas.getContext('2d');
                            canvas.width = imgWidth;
                            canvas.height = imgHeight;
                            ctx.drawImage(this, 0, 0, imgWidth, imgHeight);//根据宽高绘制图片
                            var fullQuality = canvas.toDataURL("image/png", 1.0);//canvas转为base64
                            var blogData=dataURLtoBlob(fullQuality);
                            callback(blogData);
                        }else{
                            callback(false);
                        }
                    }
                }
            } catch (e) {
                console.log("压缩失败!");
            }
        }
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值