微信小程序拍照后如何加水印?

这篇文章展示了如何在微信小程序中通过wx.chooseMedia选择图片,然后利用canvas进行图像处理,包括设置图片大小、添加阴影效果以及在图片上绘制日期文本作为水印。最后,文章描述了如何将处理后的canvas转换为临时文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<canvas id="myCanvas" type="2d"></canvas>


//调用拍摄
wx.chooseMedia({
        count: 1, //个数
        mediaType: ['image'], //类型 图片
        sourceType: ['camera'], //使用相机拍摄
        camera: 'back', //	使用后置摄像头
        success(res) {
          const path = res.tempFiles[0].tempFilePath;

          //获取图片信息
          wx.getImageInfo({
            src: path,
            success: (img) => {
              const date = _this.getCurrentDate();

              wx.createSelectorQuery()
                .select('#myCanvas')
                .fields({node: true, size: true})
                .exec((resCanvas) => {
                  // Canvas 对象
                  const canvas = resCanvas[0].node;
                  // 初始化画布大小
                  canvas.width = img.width;
                  canvas.height = img.height;
                  // 渲染上下文
                  const ctx = canvas.getContext('2d');
                  // 图片对象
                  const image = canvas.createImage();
                  // 图片加载完成回调
                  image.onload = () => {
                    // 将图片绘制到 canvas 上
                    ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

                    ctx.font='12px system-ui';
                    ctx.shadowColor='rgba(0,0,0,0.2)';
                    ctx.shadowOffsetX=2;
                    ctx.shadowOffsetY=2;
                    ctx.fillStyle='red';
                    ctx.fillText('时间 ' + date, 20, img.height - 10);
                    ctx.restore();

                    wx.canvasToTempFilePath({
                      canvas: canvas,
                      success(res) {
                        console.log(res.tempFilePath);

                      },fail(){
                        console.log('绘图日期失败!');
                      }
                    })
                  }
                  // 设置图片src
                  image.src = img.path;
                })
            },fail(){
              console.log('获取拍照图片失败!')
            }
          })
        },
        fail(){
          console.log('拍照失败!');
        }
      })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值