uni-app 实现图片上传添加水印操作

一、定义一个canvas标签,微信小程序的实现方式有所变动

	<!-- #ifdef MP-WEIXIN -->
	<canvas type="2d" id="upload-canvas" class="uploadCanvas" 
		:style="{'width':width+'px','height':height+'px','position':'absolute','z-index':'-999','left':'-1000000px'}"></canvas>
	<!-- #endif -->

	<!-- #ifdef H5 -->
	<canvas canvas-id="upload-canvas" class="uploadCanvas" 
		:style="{'width':width+'px','height':height+'px','position':'absolute','z-index':'-999','left':'-1000000px'}"></canvas>
	<!-- #endif -->

二、拿到图片后添加水印

addWatermark(fileUrl) {
			let that = this;
			return new Promise((resolve, reject) => {

				uni.getImageInfo({
					src: fileUrl, // 替换为你的图片路径
					success: async (res) => {
						console.log("res", res);
						const imageWidth = res.width;
						const imageHeight = res.height;
						that.width = imageWidth;
						that.height = imageHeight;
						await util.sleep(1000);
						// #ifdef MP-WEIXIN
						const query = wx.createSelectorQuery()
						query.select('#upload-canvas')
							.fields({
								node: true,
								size: true
							})
							.exec((resCanvas) => {
								let filePath = res.path;
								// 获取文件系统管理器
								const fs = uni.getFileSystemManager();
								// 读取图片文件为Base64编码
								fs.readFile({
									filePath: filePath,
									encoding: 'base64',
									success: function(res) {
										const base64Data = res.data;
										console.log("base64Data==",base64Data)
										const canvas = resCanvas[0].node
										canvas.width = that.width;
										canvas.height = that.height;
										const ctx = canvas.getContext('2d')
										let img = canvas
											.createImage(); // 注意是使用canvas实例 不是ctx
										img.src =
											`data:image/png;base64,${base64Data}`
										img.onload = () => {
											ctx.drawImage(img, 0, 0,that.width,that.height);
											ctx.font = '16px',
												ctx.fillStyle =
												'rgba(0, 0, 0, 1)';
											const lineHeight = 20; // 水印文字行高

											const lines = that.watermarkText
												.split('\n');
											const x = 10; // 水印左上角 x 坐标
											let y = 20; // 水印左上角 y 坐标

											lines.forEach((line) => {
												ctx.fillText(line, x,
													y);
												y += lineHeight;
											});
											ctx.stroke();
											// 保存Canvas绘制结果为临时文件
											uni.canvasToTempFilePath({
												canvas: canvas,
												success: (res) => {
													// 将临时文件路径保存到数组中
													resolve(res
														.tempFilePath
													)
												},
												fail: (error) => {
													console.error(
														'Failed to save canvas:',
														error);
												},
											});


										}
									},
									fail: function(error) {
										console.log("eee", error);
									}
								});

							})
						// #endif

						// #ifdef H5
						const ctx = uni.createCanvasContext('upload-canvas', this);
						ctx.drawImage(res.path, 0, 0, imageWidth,
							imageHeight);
						ctx.setFontSize(16);
						ctx.setFillStyle('rgba(0, 0, 0, 1)'); // 设置水印颜色和透明度
						const lineHeight = 20; // 水印文字行高
						const lines = that.watermarkText
							.split('\n');
						const x = 10; // 水印左上角 x 坐标
						let y = 20; // 水印左上角 y 坐标

						lines.forEach((line) => {
							ctx.fillText(line, x,
								y);
							y += lineHeight;
						});
						ctx.stroke();
						ctx.draw(false, () => {
							// 保存Canvas绘制结果为临时文件
							uni.canvasToTempFilePath({
								canvasId: 'upload-canvas',
								success: (res) => {
									// 将临时文件路径保存到数组中
									resolve(res.tempFilePath)
								},
								fail: (error) => {
									console.error('Failed to save canvas:',
										error);
								},
							}, this);
						});
						// #endif
					},
					fail: (error) => {
						console.error(error);
					},
				});
			})
		},

你可能感兴趣的:(uni-app)