我这里用的是uniapp上传方法
上传的方法
uni.chooseImage({
count: 6, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
// console.log(res);
this.base64AddWaterMaker(res.tempFiles[0].path, this.waterMakeConfig).then((res) => {
console.log("res", res);
this.img=res
});
}
});
//处理水印的方法
base64AddWaterMaker(base64Img, waterMakeConfig) {
// 保留this指向 后面会用到的
let _this = this;
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'Anonymous'; // 图片加载的过程中允许出现跨域
// 先有src属性才会触发 onload函数
img.src = base64Img;
// 异步加载
img.onload = function() {
// 注意img.onload方法是异步的
canvas.width = img.width;
canvas.height = img.height;
ctx.font = `40px Georgia`;
// 给文字添加颜色
// ctx.fillStyle = 'red';
// 添加渐变颜色的水印
var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'blue');
gradient.addColorStop(1, 'red');
ctx.fillStyle = gradient;
// 以左上角为坐标原点 开始绘制图像
ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.fillText(waterMakeConfig.textArray[0], img.width * 0.05, img.height *
0.8); //在图片上添加字体
ctx.fillText(waterMakeConfig.textArray[1], img.width * 0.05, img.height * 0.85);
let resultBase64 = canvas.toDataURL('image/png'); // 返回的图片文件也是base64格式的
if (!resultBase64) {
reject();
} else {
_this.imgBase64 = resultBase64;
resolve(resultBase64);
}
};
});
},
水印样式
waterMakeConfig: {
font: 'microsoft yahei', //字体
textArray: ['风-温迪', '2022/9/1 10:13'],
},
最终效果