[uniapp] Add watermark to pictures

1. Create a canvas

var context = uni.createCanvasContext('Canvas')

2. Get local pictures

uni.chooseImage({
	count: 1,
	success: (res) => {
	    var file = res.tempFilePaths[0];
	    const tempFiles = res.tempFiles[0]
    })
})

3. Get image information - add watermark

uni.getImageInfo({
		src: res.tempFilePaths[0],
		success: function(image) {
		_self.width = image.width + 'px'
		_self.height = image.height + 'px'
		setTimeout(function() {
		context.width = _self.width;
		context.height = _self.height;
		context.fillRect(0, 0, _self.width, _self.height);
		// 将图片src放到cancas内,宽高为图片大小
		context.drawImage(res.tempFilePaths[0], 0, 0, image.width, image.height)
					
		context.rotate(45 * Math.PI / 180);
		for (let i = 0; i <= 50; i++) {
		    context.beginPath();
			context.setFontSize(50);
			context.setFillStyle("rgba(169,169,169,0.4)");
			context.fillText("我是水印", 0, i * 170);
			for (let j = 0; j <= 50; j++) {
				context.beginPath();
				context.setFontSize(50);
				context.setFillStyle("rgba(169,169,169,0.4)");
				context.fillText("我是水印", j * 340, i * 170);
			}
		}
		for (let i = 0; i < 50; i++) {
			context.beginPath();
			context.setFontSize(50);
			context.setFillStyle("rgba(169,169,169,0.4)");
			context.fillText("我是水印", 0, -170 * i);
			for (let j = 1; j < 50; j++) {
				context.beginPath();
				context.setFontSize(50);
				context.setFillStyle("rgba(169,169,169,0.4)");
				context.fillText("我是水印", 340 * j, -170 * i);
			}
		}
		context.rotate(-45 * Math.PI / 180);
		uni.showLoading({
			title: '上传中...',
		})
		context.draw(false, () => {
			setTimeout(() => {
			uni.canvasToTempFilePath({
				canvasId: "Canvas",
				fileType: 'jpg',
				success: (path) => {
                        //压缩
						uni.compressImage({
								src: path.tempFilePath,
								quality: 20,
								success: res => {}
								})
								}
						})
				}, 500)
			})
		}, 1000)
    }
})

1.  _self is the this I defined globally , please define this  globally when you use it

 2. If it is not displayed, please set the font size and distance of the watermark according to the pixels of your picture

 

Guess you like

Origin blog.csdn.net/sxmzhw/article/details/127057057