教你一招:在微信小程序中为用户上传的图片添加时间水印

在微信小程序开发过程中,我们常常需要在图片上添加水印,以保护版权或增加个性化元素。本文将为大家介绍如何在微信小程序中为图片添加时间水印,让你的小程序更具特色。

实现步骤:

1. 创建页面结构

pages目录下创建一个名为uploadWatermark的文件夹,并在该文件夹中创建以下四个文件:uploadWatermark.wxmluploadWatermark.wxssuploadWatermark.jsuploadWatermark.json

2. 编写uploadWatermark.wxml
<view class="container">
  <button bindtap="chooseImage">选择图片</button>
  <image src="{{watermarkedImage}}" mode="aspectFit" class="watermarked-image" wx:if="{{watermarkedImage}}"></image>
</view>
<canvas canvas-id="watermarkCanvas" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; display: none;"></canvas>
3、编写uploadWatermark.wxss
.container {
  position: relative;
  width: 100%;
}

button {
  margin: 20px;
}

.watermarked-image {
  width: 100%;
}
4、编写uploadWatermark.js
Page({
  data: {
    watermarkedImage: '', // 添加水印后的图片
  },

  // 选择图片
  chooseImage: function() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePaths是选择的图片的本地临时文件路径列表
        that.addTimeWatermark(res.tempFilePaths[0]);
      }
    })
  },

  // 添加时间水印
  addTimeWatermark: function(imagePath) {
    const ctx = wx.createCanvasContext('watermarkCanvas', this);
    ctx.drawImage(imagePath, 0, 0, 300, 150); // 假设图片大小为300x150,根据实际情况调整

    // 设置水印文字
    const time = new Date().toLocaleString();
    ctx.setFontSize(14);
    ctx.setFillStyle('rgba(255, 255, 255, 0.5)'); // 半透明白色
    ctx.setTextAlign('right');
    ctx.fillText(time, 290, 140); // 根据实际情况调整位置

    // 绘制水印
    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'watermarkCanvas',
        success: (res) => {
          this.setData({
            watermarkedImage: res.tempFilePath
          });
        },
        fail: (err) => {
          console.error(err);
        }
      }, this);
    });
  }
});

运行效果:

在微信开发者工具中预览uploadWatermark页面。点击“选择图片”按钮,用户可以选择从相册或相机上传图片。上传后,图片将显示在页面上,并且会添加当前时间水印。

总结:

通过以上步骤,我们实现了在微信小程序中允许用户上传图片并添加时间水印的功能。这个功能不仅实用,而且可以增强用户体验。希望这个教程对你在开发微信小程序时有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jiaberrrr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值