vue+element图片压缩

//图片上传事件

handleChange(file, fileList) {

const isJPG = file.raw.type === 'image/jpeg';

const ispng = file.raw.type === 'image/png';

const isbmp = file.raw.type === 'image/bmp';

const isLt2M = file.raw.size / 1024 / 1024 < 10;

const isLt200k = file.raw.size / 1024 < 200;

const _that = this

if (!(isJPG || ispng || isbmp)) {

this.$message.error('上传头像图片只能是 JPG/png/bmp格式!');

return false

}

if (!isLt2M) {

this.$message.error('上传头像图片大小不能超过10MB!');

return false

} else if (isLt200k) { //小于200k

file.raw.url = file.url;

let data = new FormData()

data.append('file', val)

data.append('name', file.name)

//然后发请求

//this.$emit("addFile", file.raw);

}else{

this.compress(file.raw, function (val) {

//_that.$emit("addFile", val);

//再通过

let data = new FormData()

data.append('file', val)

data.append('name', file.name)

//然后发请求

})

}

},

 

//压缩方法

compress(fileObj, callback) {

try {

const image = new Image()

image.src = URL.createObjectURL(fileObj)

image.onload = function () {

const that = this

// 默认按比例压缩

let w = that.width

let h = that.height

const scale = w / h

w = fileObj.width || w

h = fileObj.height || (w / scale)

let quality = 0.7 // 默认图片质量为0.7

// 生成canvas

const canvas = document.createElement('canvas')

const ctx = canvas.getContext('2d')

// 创建属性节点

const anw = document.createAttribute('width')

anw.nodeValue = w

const anh = document.createAttribute('height')

anh.nodeValue = h

canvas.setAttributeNode(anw)

canvas.setAttributeNode(anh)

ctx.drawImage(that, 0, 0, w, h)

// 图像质量

if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {

quality = fileObj.quality

}

// quality值越小,所绘制出的图像越模糊

const data = canvas.toDataURL('image/jpeg', quality)

const bytes = window.atob(data.split(',')[1]) // 去掉url的头,并转换为byte

// 处理异常,将ascii码小于0的转换为大于0

const ab = new ArrayBuffer(bytes.length)

const ia = new Uint8Array(ab)

for (let i = 0; i < bytes.length; i++) {

ia[i] = bytes.charCodeAt(i)

}

// 压缩完成执行回调

const newFile = new Blob([ab], { type: 'image/png' })

newFile.name = fileObj.name

callback(newFile)

}

} catch (e) {

console.log('压缩失败!')

}

},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值