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

微信小程序使用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);
      }
    });
  },
相关推荐
甜甜的资料库12 小时前
基于微信小程序的睡眠宝系统源码数据库文档
数据库·微信小程序·小程序
华子w90892585912 小时前
SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现
spring boot·微信小程序·uni-app
恰薯条的屑海鸥13 小时前
关于我对各开发语言的看法与接下来的文章内容
开发语言·学习·微信小程序·网站开发·全栈开发
勿念43613 小时前
基于鸿蒙(HarmonyOS5)的打车小程序
华为·小程序·harmonyos
Stanford_110615 小时前
关于大数据的基础知识(二)——国内大数据产业链分布结构
大数据·开发语言·物联网·微信小程序·微信公众平台·twitter·微信开放平台
邹荣乐17 小时前
uni-app开发微信小程序的报错[渲染层错误]排查及解决
前端·微信小程序·uni-app
weixin_1772972206920 小时前
盲盒一番赏小程序:引领盲盒新潮流
小程序
chaosama2 天前
微信小程序带参分享、链接功能
微信小程序·小程序
胡西风_foxww2 天前
微信小程序动态组件加载的应用场景与实现方式
微信小程序·应用·加载·动态组件
ALLSectorSorft2 天前
上门服务小程序会员系统框架设计
小程序·apache