微信小程序图片添加水印并等比列缩放

index.wxml


  
    
    
  

index.wxss

.message-page {
  height: calc(100vh - 20px);
  width: 100vw;
  padding-top: 20px;
}

.choose-img {
  margin-bottom: 8px;
  margin-top: 8px;
  background-color: red;
  color: white;
}

index.js

const app = getApp()

Page({
  data: {
    imgSrc: '',
    imgWidth: 0,
    imgHeight: 0
  },
  onLoad: function() {

  },
  /**
   * 选择照片
   */
  chooseImage() {
    this.getPhoto();
  },

  /**
   * 拍照 或 从相册选择
   */
  getPhoto() {
    var _this = this;

    //获取图片
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success(res) {
        wx.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
          sourceType: [res.tapIndex === 0 ? 'camera' : 'album'],
          success: function(res) {
            // console.log(res);

            _this.setData({
              imgSrc: res.tempFilePaths[0]
            })

            //图片水印
            _this.watermark(res.tempFilePaths[0]);
          },
        })
      }
    })
  },

  /**
   * 查看图片
   */
  preViewImage(imgsrc) {

    var imgList = [];
    imgList.push(imgsrc);

    wx.previewImage({
      current: imgsrc,
      urls: imgList,
    })
  },

  /**
   * 图片水印
   */
  watermark(tempFilePath) {
    var _this = this;
    wx.getImageInfo({
      src: tempFilePath,
      success(res) {
        //计算出图片的宽高
        console.log('图片宽高' + res.width + ',' + res.height);
        console.log('屏幕宽高' + wx.getSystemInfoSync().windowWidth + ',' + wx.getSystemInfoSync().windowHeight)

        var whThan = 0;
        var imgW = 0;
        var imgH = 0;

        //1.算出图片的宽高比列
        whThan = res.width / res.height;
        //2.判断宽高比是否大于 1   
        if (whThan > 1) {
          //若大于1,则以屏幕的宽度为基准,让图片最大化显示
          imgW = wx.getSystemInfoSync().windowWidth - 16;
          imgH = imgW / whThan;
        } else {
          //若小于1,则以画布的宽度为基准,让图片最大化显示
          imgH = 300;
          imgW = imgH * whThan;
        }

        _this.setData({
          imgWidth: imgW,
          imgHeight: imgH
        })

        console.log(imgW + ',' + imgH)
        let ctx = wx.createCanvasContext('firstCanvas');
        ctx.drawImage(tempFilePath, 0, 0, imgW, imgH);
        ctx.setFontSize(20);
        ctx.setFillStyle('red');
        ctx.fillText('我是水印', 10, 30);
        ctx.draw(false);
      }

    })
  },

})

 看一下图片的分辨率

微信小程序图片添加水印并等比列缩放_第1张图片

效果

微信小程序图片添加水印并等比列缩放_第2张图片

最后附上本人做的一个小程序

   

你可能感兴趣的:(微信小程序,javascript,css,html)