当前位置: 首页 > article >正文

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

微信小程序使用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);
      }
    });
  },


http://www.kler.cn/news/361958.html

相关文章:

  • 华为OD机试 - 篮球比赛 - 递归(Java 2024 E卷 100分)
  • js 精确计算(加减乘除)
  • Java应用程序的测试覆盖率之设计与实现(二)-- jacoco agent
  • 5.redis安装【Docker】
  • 【JavaScript】Javascript基础Day02:运算符、分支、循环
  • Git 完整教程:版本管理、分支操作与远程仓库解析
  • ARM/Linux嵌入式面经(四六):华为
  • transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)的计算过程
  • qt5.12.12插件机制无法加载插件问题
  • 毕业生找工作的攻略:从校园到职场的成功之路
  • R语言绘图——文本注释
  • LLaMA Factory环境配置
  • 猎板高频PCB的制成能力分享
  • CISAW安全集成,协助组织构建坚固的信息防护堡垒
  • 【一站式学会Kotlin】第二十五 Kotlin内部类和嵌套类的区别和案例
  • 智慧交通新征程:亿维锐创与图为科技达成战略合作
  • STM32+CubeMX -- 开发辅助工具
  • 蓝桥杯基本操作和运算
  • 【某农业大学计算机网络实验报告】实验一 集线器和交换机的对比
  • excel将文本型数字转变为数值型数字
  • ppt模板一键套用怎么操作?制作ppt基础步骤手把手教你
  • Java中的异步编程模型
  • LN9361 低噪声电荷泵 DC/DC 转换器
  • 什么是缓存?
  • 群控系统服务端开发模式-业务流程图补充
  • Android使用协程实现自定义Toast