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

微信小程序使用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);
      }
    });
  },
相关推荐
程序员陆通3 小时前
零基础AI编程开发微信小程序赚流量主广告实战
微信小程序·小程序·ai编程
paopaokaka_luck3 小时前
校园快递小程序(腾讯地图API、二维码识别、Echarts图形化分析)
vue.js·spring boot·后端·小程序·uni-app
头发还在的女程序员6 小时前
ThinkPHP+Mysql 灵活用工小程序-技术深度解析与实践指南
数据库·mysql·小程序
编程猪猪侠11 小时前
解决uni-app微信小程序编译报错:unexpected character `1`
微信小程序·小程序·uni-app
2501_9159090611 小时前
iOS 签名证书全生命周期实战,从开发到上架的多阶段应用
android·ios·小程序·https·uni-app·iphone·webview
suncentwl20 小时前
论答题pk小程序软件版权的
小程序·答题小程序·答题pk·知识竞赛·答题pk软件
weixin_hcs220120 小时前
小程序打通美团核销:解锁到店综合业态私域密码,赋能6000+门店破局增长
小程序·美团团购·美团新平台·java接入美团团购·快速接入美团团购
weixin_177297220691 天前
盲盒抽谷机小程序系统开发:解锁盲盒新玩法,开启潮玩社交新时代
小程序
Hashan1 天前
微信小程序:实现证件OCR识别
前端·vue.js·微信小程序
2501_915918411 天前
iOS 文件管理全流程实战,从开发调试到数据迁移
android·ios·小程序·https·uni-app·iphone·webview