search
HomeWeChat AppletMini Program DevelopmentTake you to develop a small program to generate avatars for the Year of the Tiger Spring Festival

This article will help you follow the trend and make a small program for making avatars for the Year of the Tiger Spring Festival. Get a WeChat avatar and select the avatar frame to synthesize different Year of the Tiger Spring Festival avatars. I hope it will be helpful to everyone!

Take you to develop a small program to generate avatars for the Year of the Tiger Spring Festival

The Spring Festival is coming soon. Today I saw some netizens shared the web version of the Year of the Tiger avatar creation tool. I feel very good. I just planned to make a small program to practice. theme, then try it with this one.

First, the final rendering:

Take you to develop a small program to generate avatars for the Year of the Tiger Spring Festival

Let’s talk about the implementation process

The first step: get it first The current WeChat avatar picture, the main code is as follows. Note that the avatar picture obtained by default is not high-definition, and needs to be converted into a high-definition picture first to avoid being blurry after generation.

 getUserProfile(e) {
    console.log(e)
    let that = this;
    wx.getUserProfile({
      desc: '仅用于生成头像使用',
      success: (res) => {
        var url = res.userInfo.avatarUrl;
        while (!isNaN(parseInt(url.substring(url.length - 1, url.length)))) {
          url = url.substring(0, url.length - 1)
        }
        url = url.substring(0, url.length - 1) + "/0";
        res.userInfo.avatarUrl = url;
        console.log(JSON.stringify(res.userInfo));
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        that.drawImg();
      }
    });
  },

The second step: synthesize the avatar, obtain the local file from the material picture and the avatar picture obtained in the first step, and then use the cavas component of the mini program to synthesize it.

drawImg() {
    let that = this;
    wx.showLoading({
      title: '生成头像中...',
    })
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: that.data.userInfo.avatarUrl,
        success: function (res) {
          resolve(res);
        }
      })
    });
    var mask_id = that.data.now_mask;
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: `../../assets/img/mask0${mask_id}.png`,
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    Promise.all([
      promise1, promise2
    ]).then(res => {
      console.log(res)
      var windowWidth = wx.getSystemInfoSync().windowWidth
      var context = wx.createCanvasContext('myAvatar');
      var size = windowWidth /750 * 500
      // var size = 500
      context.drawImage(res[0].path, 0, 0, size, size);
      context.draw(true)
      context.save();
      context.drawImage('../../'+res[1].path, 0, 0, size, size);
      context.draw(true)
      context.save();

    })
    wx.hideLoading()
  },

Step 3: Download the synthesized picture to the local album.

canvasToTempFile(){
    if(!this.data.userInfo){
      wx.showModal({
        title: '温馨提示',
        content: '请先点击上方获取微信头像',
        showCancel: false,
      })
      return
    }
    var windowWidth = wx.getSystemInfoSync().windowWidth
    var size = 500
    // var dpr = 750 / windowWidth
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      height: size,
      width: size,
      canvasId: 'myAvatar',
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: result => {
            wx.hideLoading();
            wx.showModal({
              content: '图片已保存到相册,请前往微信去设置哟!',
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          }, fail(e) {
            wx.hideLoading();
            console.log("err:" + e);
          }
        })
      }
    });
  },

In this way, the main function is achieved.

Finally, put the mini program code, everyone is welcome to scan the code and experience it:

Take you to develop a small program to generate avatars for the Year of the Tiger Spring Festival

Finally, the current project has been open source: https://github. com/hackun666/new-year-face

I wish everyone a happy Spring Festival and good luck in the Year of the Tiger!

Original address: https://juejin.cn/post/7057807283463389191

Author: hackun

[Related learning recommendations: 小Program development tutorial

The above is the detailed content of Take you to develop a small program to generate avatars for the Year of the Tiger Spring Festival. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools