参考Ant Design of Vue官方文档使用transformFile:
具体代码如下:
loadStampImage() {
const img = new Image();
img.onload = () => {
this.stampImage = img;
};
img.src = '1.jpg'; // 印章图片的路径
},
transformFile(file) {//添加水印
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(file);//file转base64
reader.onload = (e) => {
const canvas = document.createElement('canvas');
const img = new Image()
img.src = e.target.result;
img.onload = () => {
let ctx = canvas.getContext('2d');
let data = ""
canvas.width = img.width;//画布宽度
canvas.height = img.height;//画布高度
ctx.drawImage(img, 0, 0);
// 在图片上绘制印章
if (this.stampImage) {
ctx.drawImage(this.stampImage, img.width-100, img.height-100); // 叠加印章图片
}
data = canvas.toDataURL(file.type); //输出压缩后的base64
//base64转file
let arr = data.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let files = new File([new Blob([u8arr], { type: mime })], file.name, { type: file.type })
files.uid = file.uid
resolve(files)
};
};
})
}
created 中调用 loadStampImage方法,img.src静态访问路径,本项目在public目录下,其他项目可能在static目录下。
添加文字水印也一样:
let ctx = canvas.getContext('2d');
let data = ""
let imgWidth = img.width;
let imgHeight = img.height;
let fontsize = imgWidth > imgHeight ? imgHeight / 10 : imgWidth / 10//设定文字大小随图片大小变化
canvas.width = imgWidth;//画布宽度
canvas.height = imgHeight;//画布高度
ctx.drawImage(img, 50, 0, imgWidth, imgHeight);//绘制图片大小和先前图片一致
ctx.fillStyle = 'rgb(96,96,96,0.1)';//水印颜色,透明度
ctx.textBaseline = 'bottom';//水印对其的基准线
ctx.font = `${fontsize}px Verdana`//文字大小
ctx.fillText('Ant Design Vue', imgWidth - 20, imgHeight - 20);//添加的文字
data = canvas.toDataURL(file.type); //输出压缩后的base64