//图片上传事件
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('压缩失败!')
}
},