微信小程序--给头像添加logo(生成海报同理)

实现给图片添加logo或者生成海报,其原理是使用canvas,用canvas绘制出想要的图片进行保存

1.在wxml文件中添加canvas

canvs层级太高,所以将它定位到屏幕外,不影响页面

<view style='width:0px;height:0px;overflow:hidden;position: absolute;top:-1000px;'>
    <canvas canvas-id='myCanvas' style='width:500px;height:500px;'></canvas>
</view>

1.上传图片

 chooseImg(){
    wx.chooseImage({
      count:1,  
      success: (res)=>{
        if (res.errMsg == "chooseImage:ok"){
          this.setData({
            headImg: res.tempFilePaths[0]
          })
        }
      }
    })
  },

2.获取添加的logo图标

//生成头像
  creatHead(){
    //调用接口,获取添加到头像的icon图标
    // WXAPI.getIcon() 调用接口
    WXAPI.getIcon().then(res=>{
    //将网络图片转换为本地图片(res.data:图片地址)
    	this.handleNetImg(res.data).then((resImg, err)=>{
			if (err){
				 wx.showToast({
				    title: '图片获取错误',
				    icon: "none"
				  })
				  return;
			 }
			 this.setData({
				   headIcon: resImg.path
			 })
			 //绘制头像
			 this.creatCanvas();
			})
    })
    
  },
//网络图片转为本地图片
  handleNetImg(imagePath) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imagePath,
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res)
        }
      });
    });
  },

生成海报与给图片添加logo的不同点在于获取小程序码

	//QrCodedata 传给后端参数
	let QrCodedata = {
		scene: "fromNumber=" + this.data.FNumber,
		page: "pages/login/login",
		width: 400,
	}
	//获取小程序码(我这里获取到的是Base64)
	WXAPI.shareQRCode(QrCodedata).then(res=> {
		let imgPath = wx.env.USER_DATA_PATH + '/index' + 'qrcode' + '.png';
		let imageData = res.data.replace(/^data:image\/\w+;base64,/, "");
		let fs = wx.getFileSystemManager();
		fs.writeFileSync(imgPath, imageData, "base64");
		this.headIcon = imgPath;
	})

3.绘制canvas

// 绘制头像
  creatCanvas(){
    let _this = this;
    let ctx = wx.createCanvasContext('myCanvas', _this );
    //drawImage 的参数查找官网
    ctx.drawImage(this.data.headImg, 20, 20, 460, 460); //绘制上传的照片
    ctx.drawImage(this.data.headIcon, 345, 340, 150, 150);//绘制添加的logo图片
    ctx.draw(true, () => {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: (res) => {
          	//将绘制完成的图片赋值给变量
            this.setData({
              showImg: res.tempFilePath,
            })
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '生成失败!',
              icon: "none"
            })
          },
        }, _this);
      }, 300);
    });
  },

4.canvas画完了,接着就是保存它

//保存图片前判断是否拥有保存到相册权限
  getPhotosAlbumAuth() {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          _this.saveImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              _this.saveImg();
            },
            fail() {
              wx.showToast({
                title: '您没有授权,无法保存到相册',
                icon: 'none'
              })
            }
          })
        } else {
          wx.openSetting({
            success(result) {
              if (result.authSetting['scope.writePhotosAlbum']) {
                _this.saveImg();
              } else {
                uni.showToast({
                  title: '您没有授权,无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
//保存头像
  saveImg() {
    var _this = this;
    wx.saveImageToPhotosAlbum({
      filePath: _this.data.showImg,
      success(data) {
        wx.showToast({
          title: "图片保存成功",
          icon: "success",
          mask: true
        })
      },

    })
  },

你可能感兴趣的:(微信小程序,生成海报,图片添加logo)