小程序上传图片加水印

513 阅读1分钟

在微信小程序开发过程中,常常需要在图片上添加水印,效果如下图所示: GIF 2024-11-29 10-14-01.gif a22b90546b9544c199e357f046252101.png

小程序添加水印代码仓库

实现代码

<image src="{{src}}" mode="aspectFit" lazy-load="false" wx:if="{{src}}"></image>

<view class="upload-img" bind:tap="uploadIMG"> + </view>

<canvas canvas-id="myCanvas" 
style="width: {{canvasWidthValue}}px;height:{{canvasHeightValue}}px;
position:fixed;top:1000vh;z-index:-1"
></canvas>
  uploadIMG() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: async res => {
        wx.showLoading({
          title: '上传中...',
          mask: true,
        });
        const address = '深圳市南山区学府路263号大新时代大厦A座';
        const currentTime = new Date().toLocaleString();
        const data = res.tempFiles[0];
        try {
          const ctx = wx.createCanvasContext('myCanvas');
          // 获取图片真实的宽度和高度
          const res = await wx.getImageInfo({
            src: data.path ? data.path : data.tempFilePath ? data.tempFilePath : '',
          });
          console.log('获取图片真实的宽度和高度=>', res);
          this.setData({
            canvasWidthValue: res.width,
            canvasHeightValue: res.height,
          });
          // 绘制图片
          ctx.drawImage(data.tempFilePath, 0, 0, res.width, res.height);
          // 添加水印
          ctx.setFontSize(20);
          ctx.fillText(address, 10, res.height - 50); // 地址水印
          ctx.fillText(currentTime, 10, res.height - 20); // 时间水印
          ctx.draw();
          setTimeout(async () => {
            const temp = await wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
            });
            // **上传水印图片到服务器(真实项目中需要考虑上传后台,还是直传等)**
            // const result = await request.uploadFile(temp.tempFilePath);
            this.setData({
              src: temp.tempFilePath,
            });
            wx.hideLoading();
          }, 100);
        } catch (error) {
          console.log('error=>', error);
        }
      },
    });
  },