async handleGetFile(file) {
if (file.size / 1024 / 1024 > 15) {
this.$Message.error(`文件大小最大为15M`)
return
}
this.showUpLoadImage(file, file.name)
},
//处理文件显示
showUpLoadImage(file, fileName) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
let fileType = reader.result.split(';')[0].split('/')[1]
this.drawCanvas(reader.result, fileName, fileType)
}
},
drawCanvas(img, fileName, fileType) {
let image = new Image()
image.src = img
image.onload = () => {
let c = document.getElementById("canvas");
c.height = 100
c.width = 100
let ctx = c.getContext("2d");
ctx.drawImage(image, 25, 25, 50, 50);
// 将canvas的透明背景设置成白色
let imageData = ctx.getImageData(0, 0, c.width, c.height);
for(let i = 0; i < imageData.data.length; i += 4) {
// 当该像素是透明的,则设置成白色
if(imageData.data[i + 3] === 0) {
imageData.data[i] = 255;
imageData.data[i + 1] = 255;
imageData.data[i + 2] = 255;
imageData.data[i + 3] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
ctx.beginPath();
ctx.arc(50,50, 47,0,2*Math.PI, false);
ctx.lineWidth = 3
ctx.strokeStyle = "#436BF6"
ctx.stroke();
ctx.closePath();
let dataURL = c.toDataURL('image/' + fileType)
let blob = this.dataURLtoBlob(dataURL)
let file = this.blobToFile(blob, fileName)
//将文件转换为formDate格式
const formData = new FormData();
file = new File([file], fileName)
formData.append('file', file)
this.$api.picture.addPicture(formData).then(res => {
if (res.success) {
this.imageList.push({
id: res.obj.id,
builtin: false,
image: dataURL
})
this.$Message.success(res.msg || '图片上传成功')
} else {
this.$Message.error(res.msg || '图片上传失败')
}
})
}
},
//将base64转换为blob
dataURLtoBlob(dataurl) {
let 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 });
},
//将blob转换为file
blobToFile(theBlob, fileName){
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
},
效果图: