小程序调取相机照片添加水印(时间水印)

下面的代码主要就是你在小程序调用了相机或者相册后,在返回的照片上添加水印。

WXML

<view style="width: 0;height: 0;overflow: hidden;position:fixed;left: 200%;">
  <canvas canvas-id="firstCanvas" class="canvas" style="width: {{w}}px;height: {{h}}px;"></canvas>
</view>

JS

Photograph(){ //点击拍照的方法
	let that = this
	wx.chooseImage({
		count: 1,//允许的上传总数
		quality: 'high',//图片质量
		sizeType: ['compressed'],
		sourceType: ['camera'],//支持相机和相册
		success: function(res) {
			console.log(res.tempFilePaths[0])
			wx.showLoading({
				title: "正在加载图片",
				mask: true
			})
			//获取原图片信息
			wx.getImageInfo({
				src: res.tempFilePaths[0],
				success: function (res) {
					console.log(res)
					var width = res.width, height = res.height;
					that.setData({//设定画布的宽高
						w: width,
						h: height
					})
					//获取当前时间
					let newDate = new Date();
					let year = newDate.getFullYear() //年
					let month = newDate.getMonth() + 1 //月
					let day = newDate.getDate() //日
					var hour = newDate.getHours()
					var minute = newDate.getMinutes()
					var second = newDate.getSeconds()
					let roleNameInfo = '拍摄时间:' + year + '年' + month + '月' + day + '日 '+hour+':'+minute+':' +second
					//创建canvas
					const ctx = wx.createCanvasContext('firstCanvas');
					ctx.drawImage(res.path, 0, 0, width, height); //先画出图片
					//将声明的时间放入canvas
					ctx.setFontSize(24) //注意:设置文字大小必须放在填充文字之前,否则不生效
					ctx.setFillStyle('black');
					ctx.fillText(roleNameInfo, 60, height - 60);

					ctx.draw(false, function () {
						setTimeout(function(){
							//绘画完成回调
							//生成图片
							wx.canvasToTempFilePath({
								quality: 1,
								fileType: 'jpg',
								canvasId: 'firstCanvas',
								success: function (ress) {
									console.log(ress)
									wx.uploadFile({ //将带有水印的图片上传到服务器
										url: app.globalData.site.webSite + '/api/v1/file/stream',
										filePath: ress.tempFilePath,
										name: 'file',
										success(_res) {
											let data = JSON.parse(_res.data);
											if (data.success) {
												console.log(data.data)
												wx.hideLoading();
												that.setData({
													storesPhoto: data.data
												})
											}
										}
									})
									wx.saveImageToPhotosAlbum({  //将带有水印的图片保存到相册里
										filePath: ress.tempFilePath,
										success(resp) {
											
										}
									})
									console.log(ress.tempFilePath);//ress.tempFilePath就是带有水印的图片路径
								}
							})
						},600)
					})
				}
			})
		}
	})
},

这个因为我们的要求只加了时间,大家还想添加什么东西都可以在canvas里面画出来。

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值