uniapp图片上传设置水印

时间:2022-07-09 00:42:35

1.使用uni.chooseImage上传图片

uploadImage() {
	var that = this;
	//弹出操作菜单选择拍照还是从相册选择
	uni.showActionSheet({
		itemList: ['拍摄', '从相册选择'],
		success: function(res) {
			const tapIndex = res.tapIndex;
			uni.chooseImage({
				count: 2,//最多可以选择的图片张数
				sizeType: ['compressed'],//original 原图,compressed 压缩图,默认二者都有
				sourceType: res.tapIndex == 0 ? ['camera'] : ['album'],//0-拍摄,1-从相册选择
				async success(res) {
					//后台获取时间用日期打水印(不在前端获取时间,是因为防止用户修改手机时间)
					var time = await that.getCurrentTime();
					var arr = res.tempFilePaths;//图片的本地文件路径列表
					var arrFileName = res.tempFiles;//图片的本地文件列表,每一项是一个 File 对象
					for (var i = 0; i < arr.length; i++) {
						(function(i){
							//添加水印的方法
							that.setWatermark(async bloburl => {
								//文件上传服务器
								var obj = await that.uploadFile(bloburl,encodeURI(arrFileName[i].name));
								that.list.push(obj);
							}, arr[i], time);
						})(i);
					}	
				},	
			})
		},
	});	
}

2.getCurrentTime()方法从后端获取时间作为水印

getCurrentTime() {
	var that = this;
	return new Promise((resolve, reject) => {
		var params = {
			data: '',
			header: {
				'Content-Type': 'application/json',
			}
		}
		//import API form 'xxx.js',引入api文件,调用获取时间接口
		API.currentTime(params).then(res => {
			if (res.code == 200) {
				resolve(res.data);
			} else {
				UI.toast(res.msg);
			}
		})
	})
},		

3.setWatermark方法添加水印

setWatermark(callback, blobUrl, text, quality) { //callback 回调函数 (必填),图片 blobUrl(必填),text 水印文字 ,quality 质量比率
	//获取原图分辨率
	uni.getImageInfo({
		src: blobUrl,
		success(image) {
			var width;
			var height;
			if (image.width > image.height) {
				width = 1080;
				let d = 1080 / image.width;
				height = Math.trunc(d * image.height);
			} else {
				height = 1080;
				let d = 1080 / image.height;
				width = Math.trunc(d * image.width);
			}
			var canvasImg = document.createElement('canvas');
			var ctxImg = canvasImg.getContext("2d");
			//创建1080P图片
			var img = new Image();
			img.src = image.path;
			img.width = width;
			img.height = height;
			canvasImg.width = img.width;
			canvasImg.height = img.height;
			img.onload = () => {
				ctxImg.drawImage(img, 0, 0, img.width, img.height);
				if (text != null && text.length > 0) {
					// 创建水印canvas
					var canvas = document.createElement('canvas');
					canvas.id = "canvas";
					// 设置canvas画布大小  宽度 == 字符数量*字体大小
					canvas.width = 40 * text.length;
					canvas.height = 200;
					var ctx = canvas.getContext('2d');
					ctx.rotate(6.10); // 水印旋转角度 
					ctx.font = '40px Arial';
					ctx.fillStyle = '#ff0000';
					ctx.fillText(text, 20, 100); // 水印在画布的位置x,y轴 
					canvasImg.getContext("2d").drawImage(canvas, 0, 0);
				}
				//压缩
				if (quality == null) {
					quality = 0.6; //默认质量比率
				}
				canvasImg.toBlob(blob => {
					const url = window.URL.createObjectURL(blob);
					callback(url);
				}, "image/jpeg", quality);
			}
		}
	});
},				

4.uploadFile方法把水印图片上传服务器

uploadFile(filePath, name) { //filePath图片地址,name图片名称
	var that = this;
	var params = {
		data: filePath,
		header: {
			'Content-Type': 'application/json',
			'suffix':name, //我这里把文件名上传到header里面了
		}
	}
	return new Promise((resolve, reject) => {
		//import API form 'xxx.js',引入api文件,调用上传图片接口
		API.watermarkUploadFile(params).then(res => {
			//后端返回的json字符串格式这里转一下
			var res = JSON.parse(res);
			if (res.code == 200) {
				resolve(res.data);
			} else {
				UI.toast(res.msg);
			}
		})
	})
},

5.效果图 uniapp图片上传设置水印