H5\uniapp图片添加水印

这篇博客介绍了如何在H5和uniapp中实现图片水印功能。通过uni.chooseImage选取图片,uni.getImageInfo获取图片信息,然后使用uni.createCanvasContext创建画布并设置水印文字,包括时间、用户名和地理位置。最后,将处理后的图片保存为新的临时文件路径。

H5## 标题

图片加水印
	</div>
</body>
<script>
    function blobToImg(blob) {
        return new Promise((resolve, reject) => {
          let reader = new FileReader()
          reader.addEventListener('load', () => {
            let img = new Image()
            img.src = reader.result
            img.addEventListener('load', () => resolve(img))
          })
		  console.log(blob)
          reader.readAsDataURL(blob)
        })
      }
    
      function imgToCanvas(img) {
        let canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0)
        return canvas
      }
    
      function watermark(canvas, text) {
        return new Promise((resolve, reject) => {
          let ctx = canvas.getContext('2d')
          // 设置填充字号和字体,样式
          ctx.font = "24px 宋体"
          ctx.fillStyle = "#FFF"
          // 设置右对齐
          ctx.textAlign = 'right'
          // 在指定位置绘制文字,这里指定距离右下角20坐标的地方
		  let chr = text.split("")
		  let temp = ""
		  let row = []
		  console.log(chr)
		  for (let a = 0; a<chr.length;a++){
			  if( ctx.measureText(temp).width < 220 && ctx.measureText(temp+(chr[a])).width <= 220){//220水印宽度
				  temp += chr[a];
			  }else{
				  row.push(temp);
				  temp = chr[a];
			  }
			  console.log(temp,chr[a])
		  }
		  row.push(temp)
		  console.log(row)
		  for(let b=0;b<row.length;b++){
			  ctx.fillText(row[b], canvas.width - 20, (canvas.height - 150)+(b+1)*30)//每行字体y坐标间隔30
		  }
          // ctx.fillText(row[b], canvas.width - 20, canvas.height - 20)
          canvas.toBlob(blob => resolve(blob))
        })
      }
    
      function imgWatermark(dom, text) {
        let input = document.createElement('input')
        input.setAttribute('type', 'file')
        input.setAttribute('accept', 'image/*')
        input.onchange = async () => {
		console.log(input.files[0])
		let img = await blobToImg(input.files[0])
		let canvas = imgToCanvas(img)
		let blob = await watermark(canvas, text)
		let newImage = await blobToImg(blob)
		dom.appendChild(newImage)
	  }
        dom.appendChild(input)
      }
    
      let dom = document.querySelector('#container')
	  console.log(dom)
      imgWatermark(dom, '            16:302022/06/22 星期三我在这里')
</script>

uniapp

var that = this;
uni.chooseImage({
count:1, //默认9
sizeType: [‘original’, ‘compressed’], //可以指定是原图还是压缩图,默认二者都有
sourceType: [‘album’, ‘camera’], //从相册选择
success: (res) => {
uni.getImageInfo({
src:res.tempFilePaths[0],
success: (ress) => {
console.log(ress)
that.w = ress.width / 3 + ‘px’; //3可修改
that.h = ress.height / 3 + ‘px’; //3可修改
let ctx = uni.createCanvasContext(‘firstCanvas’,that); /** 创建画布 */
setTimeout(()=>{//此处加延迟 可以避免图片的不完整
//将图片src放到cancas内,宽高为图片大小
ctx.drawImage(res.tempFilePaths[0], 0, 0, ress.width /3, ress.height/3) //与上面宽高一致
ctx.setFontSize(12) //字号
ctx.setFillStyle(‘#fff’); //颜色
that.nowTime= moment().format(“YYYY/M/D hh:mm:ss “);
that.weekText=that.getWeek ()
//多行水印 通过循环添加水印或者直接单行水印写多个
let text =that.nowTime+that.weekText+’ ‘+uni.getStorageSync(‘USER’).name+’ '+‘南京市’
let chr = text.split(””)
let temp = “”
let row = []
for (let a = 0; a < chr.length; a++) {
if (ctx.measureText(temp).width < 120 && ctx.measureText(temp +(chr[a])).width <= 120) {
temp += chr[a];
} else {
row.push(temp);
temp = chr[a];
}
}
row.push(temp)
for (let b = 0; b < row.length; b++) {
ctx.fillText(row[b],ress.width / 3 * 0.5, (ress.height / 3 * 0.4) + (b + 1) * 15) //0.5 数值越大越靠右 0.4数值越大越往下
}
//单行添加水印
ctx.fillText(text,ress.width / 3 * 0.5, (ress.height / 3 * 0.4) + (b + 1) * 15) //0.5 数值越大越靠右 0.4数值越大越往下
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: ‘firstCanvas’,
success: (res1) => {
that.src=res1.tempFilePath//加过水印的图片
},
fail(err) {
console.log(err)
}
},that);
});
},500)
}
})
},
fail: function(err) {
console.log(err)
}
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值