微信小程序上传图片添加水印

微信小程序使用wx.chooseMedia拍摄或从手机相册中选择图片并添加水印,

代码如下:

复制代码
// WXML代码:

<canvas canvas-id="watermarkCanvas" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;"></canvas>
<button bindtap="addWatermark">选择图片并添加水印</button>

// js代码:

data: {
    canvasWidth: 0,
    canvasHeight: 0

},

addWatermark() {
    // 是否清空页面上的视觉效果
    this.setData({
      canvasWidth: 0,
      canvasHeight: 0
    });

    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        wx.getImageInfo({
          src: tempFilePath,
          success: (imageInfo) => {
            // 获取屏幕宽度
            const systemInfo = wx.getSystemInfoSync();
            const screenWidth = systemInfo.screenWidth;        
            // 计算图片在canvas中的大小,保持原始宽高比
            const scale = screenWidth / imageInfo.width;
            const canvasWidth = screenWidth;
            const canvasHeight = imageInfo.height * scale;
            // 更新 canvas 尺寸
            this.setData({
              canvasWidth: canvasWidth,
              canvasHeight: canvasHeight
            }, () => {
              // 在 setData 回调中创建 canvas 上下文,确保尺寸已更新
              const ctx = wx.createCanvasContext('watermarkCanvas');
              // 清空 canvas
              ctx.clearRect(0, 0, canvasWidth, canvasHeight);          
              // 绘制原图,铺满整个canvas
              ctx.drawImage(tempFilePath, 0, 0, canvasWidth, canvasHeight);              
              // 设置水印样式
              ctx.setFontSize(16);  // 固定字体大小为16px
              ctx.setFillStyle('rgba(255, 255, 255, 0.5)');
              ctx.setShadow(2, 2, 2, 'rgba(0, 0, 0, 0.5)');
              ctx.rotate(-Math.PI / 6);
              // 添加水印文字
              const watermarkText = '我的水印';
              const textWidth = ctx.measureText(watermarkText).width;
              const xGap = textWidth * 2;  // 增加横向间距
              const yGap = 48;  // 增加纵向间距
              // 确保水印覆盖整个canvas,包括旋转后的边角
              const diagonal = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
              for (let y = -diagonal; y < diagonal * 2; y += yGap) {
                const rowOffset = ((y / yGap) % 2) * (xGap / 2);  // 偶数行错开半个宽度
                for (let x = -diagonal - rowOffset; x < diagonal * 2; x += xGap) {
                  ctx.fillText(watermarkText, x, y);
                }
              }
             
              ctx.draw(false, () => {
                wx.canvasToTempFilePath({
                  canvasId: 'watermarkCanvas',
                  success: (res) => {
                    const watermarkedImagePath = res.tempFilePath;
                    console.log(watermarkedImagePath, 'watermarkedImagePath')
                    // 上传图片的方法
                    this.uploadImage(watermarkedImagePath);
                  },
                  fail: (error) => {
                    console.error('Canvas to image failed:', error);
                  }
                });
              });
            });
          },
          fail: (error) => {
            console.error('Get image info failed:', error);
          }
        });
      },
      fail: (error) => {
        console.error('Choose media failed:', error);
      }
    });
  },
相关推荐
春哥的研究所1 小时前
AI人工智能名片小程序源码系统,名片小程序+分销商城+AI客服,包含完整搭建教程
人工智能·微信小程序·小程序
paopaokaka_luck1 小时前
智能推荐社交分享小程序(websocket即时通讯、协同过滤算法、时间衰减因子模型、热度得分算法)
数据库·vue.js·spring boot·后端·websocket·小程序
贝格前端工场2 小时前
小程序订阅消息设计:用户触达与隐私保护的平衡法则
大数据·小程序
weixin_lynhgworld2 小时前
盲盒一番赏小程序:用科技重新定义“未知的快乐”
科技·小程序
Bruce_Json3 小时前
微信小程序ts+sassjlin-ui
微信小程序·小程序·sass
来碗盐焗星球5 小时前
记一次微信小程序AI开发的血泪史
前端·微信小程序
说私域6 小时前
淘宝直播与开源链动2+1模式AI智能名片S2B2C商城小程序的融合发展研究
人工智能·小程序·开源
说私域9 小时前
互联网生态下赢家群体的崛起与“开源AI智能名片链动2+1模式S2B2C商城小程序“的赋能效应
人工智能·小程序·开源
The_era_achievs_hero16 小时前
微信小程序71~80
微信小程序·小程序
dssxyz18 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app