vue + element 压缩图片

vue + element 上传文件组件压缩图片

// 压缩图片
// 传入文件本体 e
// 因为需求限制 传入图片大小限制在500k以内
export function compressImage(e){
    return new Promise((resolve, reject)=> {
        let thumb = ''
        let isLt1M = e.size / 1024 / 1024 < 0.5;
        if (!isLt1M) {
            reject()
        }
        let img = new Image();
        let reader = new FileReader()
        // 缩放图片需要的canvas
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        // 图片转 base64 格式,方便获知图片原始尺寸
        reader.readAsDataURL(e);
        reader.onload = function(e) {
            img.src = e.target.result;
            // 图片原始尺寸
            img.onload = function () {
                // 图片原始尺寸
                let originWidth = this.width;
                let originHeight = this.height;
                // 最大尺寸限制
                let maxWidth = 64, maxHeight = 64;
                // 目标尺寸
                let targetWidth = originWidth, targetHeight = originHeight;
                // 图片尺寸超过400x400的限制
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        // 更宽,按照宽度限定尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                // canvas对图片进行缩放
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                // 清除画布
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 图片压缩
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
            
                thumb = canvas.toDataURL('image/jpeg')
                if (img.src.length === 0) {
                    reject(false)
                }
                let imgdata = {
                    content: img.src.slice(img.src.indexOf(',') + 1,img.src.length),
                    thumb: thumb.slice(thumb.indexOf(',') + 1,thumb.length),
                }
                resolve(imgdata)
            }
        };
    })
}

// 调用
      async materialUpload(file) {
        let isLt1M = file.size / 1024 / 1024 < 0.5;
        if (!isLt1M) {
          this.$message.warning('上传文件大小不能超过 500kb!');
        }
        this.fileimg = await this.$utils.compressImage(file)
      }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值