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

微信小程序使用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);
      }
    });
  },
相关推荐
Stanford_11061 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
2501_915909062 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
知识分享小能手4 小时前
微信小程序入门学习教程,从入门到精通,微信小程序核心 API 详解与案例(13)
前端·javascript·学习·react.js·微信小程序·小程序·vue
2501_915106327 小时前
JavaScript编程工具有哪些?老前端的实用工具清单与经验分享
开发语言·前端·javascript·ios·小程序·uni-app·iphone
Terio_my7 小时前
微信小程序开发从零基础到项目发布的全流程实战教程(四)
微信小程序·小程序
2501_916013748 小时前
iOS 上架 App 全流程实战,应用打包、ipa 上传、App Store 审核与工具组合最佳实践
android·ios·小程序·https·uni-app·iphone·webview
2501_915106328 小时前
iOS 26 能耗监测全景,Adaptive Power、新电池视图
android·macos·ios·小程序·uni-app·cocoa·iphone
Stanford_110610 小时前
关于嵌入式硬件需要了解的基础知识
开发语言·c++·嵌入式硬件·微信小程序·微信公众平台·twitter·微信开放平台
明月(Alioo)10 小时前
用AI帮忙,开发刷题小程序:软考真经微信小程序API接口文档(更新版)
微信小程序·小程序
克里斯蒂亚诺更新16 小时前
微信小程序的页面生命周期 以及onShow的应用场景
微信小程序·小程序