Get the AccessToken first
The AccessToken of Baidu AI interface is valid for one month. In order to demonstrate the effect, it is given priority to obtain and write it in the applet. For the convenience of follow-up. It is best to obtain it automatically and regularly. I don't want to rely on the back-end language. Then consider the cloud development of wechat applet. This article will use the method of obtaining fixed information and writing it in the relevant code of the applet Get the AccessToken interface address https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu#%E8%8E%B7%E5%8F%96access-token
Replace the APIKEY and SECRETKEY in the URL with the real value applied by yourself
https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=APIKEY&client_secret=SECRETKEY
You can quickly obtain the AccessToken by using programming language, browser and POSTMAN. Enter the URL after the above replacement directly in the browser address bar and press enter to get the AccessToken. The following JSON string is returned. We just need access_ The value of token
{ "refresh_token": "25.123456789730ffc9dbd89ec5a4952a56.315360000.1893997048.282335-12345678", "expires_in": 2592000, "session_key": "9mzdAqFbzEpjT/tsQOgi4BoWEgc5jOYlr5Lau0lCBk9BNX3ed/UEEWCOunVvz8+AMf8a/IvhjWUbWpcmtTRPvYRALNSCkA==", "access_token": "24.12345678982e904de41e99fa7c213a1f.2592000.1581229048.282335-12345678", "scope": "brain_selfie_anime brain_image_definition_enhance public brain_all_scope brain_colourize brain_stretch_restore brain_dehaze brain_contrast_enhance brain_image_quality_enhance brain_style_trans brain_inpainting wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test jurisdiction vis-classify_flower lpq_to open up cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_to open up Scope vis-ocr_Avatar assistant idl-video_Avatar assistant", "session_secret": "efeb1f7cfd0330f04b81925097b61ec8" }
AccessToken is written in the code
Add baidu.com in the utils folder of wechat applet JS and write the following
/** * Call Baidu AI sample code */ let accessToken = '24.12345678982e904de41e99fa7c213a1f.2592000.1581229048.282335-12345678'//Your own accessToken can be encapsulated according to the actual situation, and the token can be obtained automatically let faceAnimeUrl = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime';// Portrait animation
Writing method calls face animation interface
/** * Portrait animation * @param imgData base64 of picture */ let faceAnimeRequest = (imgData,callback)=>{ //Splicing interface body parameters let params = { image: imgData, } //Send interface request wx.request({ //The interface address of the splicing request. Please pay attention to access_token is a URL parameter, not a body parameter url: faceAnimeUrl + '?access_token=' + accessToken, data: params, header: { //This is based on the requirements of the interface document. If json is required, modify it to application/json 'content-type': 'application/x-www-form-urlencoded' }, method: 'POST', success: function (res) { callback.success(res.data) }, fail: function (res) { if (callback.fail) callback.fail() } }) }
Expose the method
//Exposed interface module.exports = { faceAnimeRequest: faceAnimeRequest }
baiduai.js complete code
/** * Call Baidu AI sample code */ let accessToken = ''//Your own accessToken can be encapsulated according to the actual situation, and the token can be obtained automatically let faceAnimeUrl = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime';// Portrait animation /** * Portrait animation * @param imgData base64 of picture */ let faceAnimeRequest = (imgData,callback)=>{ //Splicing interface body parameters let params = { image: imgData, } //Send interface request wx.request({ //The interface address of the splicing request. Please pay attention to access_token is a URL parameter, not a body parameter url: faceAnimeUrl + '?access_token=' + accessToken, data: params, header: { //This is based on the requirements of the interface document. If json is required, modify it to application/json 'content-type': 'application/x-www-form-urlencoded' }, method: 'POST', success: function (res) { callback.success(res.data) }, fail: function (res) { if (callback.fail) callback.fail() } }) } //Exposed interface module.exports = { faceAnimeRequest: faceAnimeRequest }
Write a page to add a page for user interaction
The requirement is base64 of the picture It is impossible for users to submit base64 data of pictures. Then we need to write a process of uploading pictures instead of the way users submit picture base64 data
In index Write the following in the wxml page
<view class="page-body"> <view class="page-body-wrapper"> <image src="{{ img }}" bindtap='preview' style="width:100%;height:800rpx;" id="imageDom" mode='aspectFit' /> </view> <button bindtap="uploads" class="up">photograph/Select picture recognition</button> <view class="footer">The effect is for entertainment only. Non facial images will also return during the test</view> </view>
Without any style, it's in index Write the following style code in the wxss page
.up { color: rgb(255, 255, 255); font-size: 20px; font-family: Microsoft YaHei ; width: 200px; height: 50px; vertical-align: middle; text-align: center; line-height: 45px; border-radius: 25px; background-color: rgb(26, 160, 225); } .page-body-wrapper image{ background: #ececec; } image { width: 100%; height: 100%; max-height: 1 } .msg { margin: 10px 0; text-align: center; } .table { margin-top: 10rpx; border: 0px solid darkgray; width: 100%; } .tr { display: flex; width: 100%; justify-content: center; height: 80rpx; } .td { font-family: Microsoft YaHei ; font-size: 28rpx; width:100%; display: flex; justify-content: center; text-align: center; align-items: center; } .bg-g{ background: white; } .baikeform{ font-size: 20rpx; color: #c0c0c0; border-top: 1rpx solid #eeeeee; margin:30rpx 40rpx 0rpx 40rpx; padding: 20rpx; } .th { font-size: 28rpx; width: 48%; justify-content: center; background: #3366FF; color: #fff; display: flex; height: 80rpx; align-items: center; } .preview-tips { margin: 50rpx 0 30rpx; } .video { margin: 20rpx auto; width: 100%; height: 300px; } switch{ zoom: 0.8; } page { background-color: #F8F8F8; height: 100%; font-size: 32rpx; line-height: 1.6; } .weui-cell_ft{ font-size: 32rpx; } .page-body-wrapper { display: flex; flex-direction: column; align-items: center; width: 100%; } .btn-area { margin-top: 40rpx; box-sizing: border-box; width: 100%; padding: 0 30rpx; } .footer{ font-size: 30rpx; text-align: center; color: #7367F0; }
The following rendering will be displayed

Write interactive functions to make the page function move
Index. Is required JS introduces Baidu AI Add img variables in JS files and data, add events to buttons, and judge the size of pictures selected by users
Xiaoshuai has finished writing here at one go.
var app = getApp(); //Introduce baidu.com js var api = require('../../utils/baiduai.js'); Page({ data: { motto: 'Animation Avatar', img: '' }, onShareAppMessage: function () { return { title: 'Animation Avatar', path: '/pages/index/index', imageUrl: '../../images/sharefaceanime.jpg', success: function (res) { if (res.errMsg == 'shareAppMessage:ok') { wx.showToast({ title: 'Share success', icon: 'success', duration: 500 }); } }, fail: function (res) { if (res.errMsg == 'shareAppMessage:fail cancel') { wx.showToast({ title: 'Share cancel', icon: 'loading', duration: 500 }) } } } }, //Select Picture binding event uploads: function () { var that = this var takephonewidth var takephoneheight wx.chooseImage({ count: 1, // Default 9 sizeType: ['compressed'], // You can specify whether to use the original or compressed image. Both are available by default sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera. Both are available by default success: function (res) { wx.getImageInfo({ src: res.tempFilePaths[0], success(res) { takephonewidth = res.width, takephoneheight = res.height } }) // Returns the list of local file paths of the selected photo. tempFilePath can display the picture as the src attribute of img tag if (res.tempFiles[0].size > (4096 * 1024)) { wx.showToast({ title: 'The picture file is too large', icon: 'none', mask: true, duration: 1500 }) } else { wx.showLoading({ title: "In analysis...", mask: true }), that.setData({ img: res.tempFilePaths[0] }) } //Read the base64 of the picture according to the uploaded picture var fs = wx.getFileSystemManager(); fs.readFile({ filePath: res.tempFilePaths[0].toString(), encoding: 'base64', success(res) { //Get the base64 of the picture and request the face animation interface api.faceAnimeRequest(res.data, { success(res) { wx.hideLoading(); that.setData({ img: 'data:image/png;base64,' + res.image }) } }) } }) }, }) }, /** * Click view picture to save */ preview(e) { var that = this; wx.previewImage({ urls: [that.data.img], current: that.data.img }) } });
See an effect

Java language API call
The AccessToken obtained earlier needs to be used
FileUtil, Base64Util and HttpUtil are officially provided by Baidu. Xiaoshuai's download address is here http://aixiaoshuai.mydoc.io/?t=234826
import com.alibaba.fastjson.JSONObject; import java.io.FileOutputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.Base64; /** * @Description Face animation example code * @author Xiaoshuai * @className FaceAnimeAPISample * @Date 2020/1/10 **/ public class FaceAnimeAPISample { /** Coding format */ private static String ENCODING_UTF_8 = "UTF-8"; public static void main(String[] args) throws Exception{ /** accessToken required by the interface */ String accessToken = ""; /** Interface address */ String api_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"; /** Picture address */ String imgaePath = "F:\\testimg\\demo-card-2.jpg"; /** Picture to byte */ byte[] imageByte = FileUtil.readFileByBytes(imgaePath); /** Picture byte to base64 */ String imgBase64 = Base64Util.encode(imageByte); /** Parameters required to assemble the interface */ String param = "image="+ URLEncoder.encode(imgBase64, ENCODING_UTF_8); /** Content returned by the request interface */ String result = HttpUtil.post(api_url, accessToken, param); /**After reading the interface document, it is clear that the returned image is base64. It's not a picture address or anything else. We need to deal with it extra. * Xiaoshuai uses fastjson to convert the interface content into Object, read the image value (i.e. Base64 of the image) and save it into a picture file */ JSONObject object = JSONObject.parseObject(result); //Get the base64 of the picture and save it as a picture file GenerateImage(object.getString("image"),"F:\\testimg\\demo-card-2110.jpg"); } /** * base64 Convert string to picture * @param imgStr Image base64 data returned by interface * @param imgFilePath The local path of the picture to be saved contains the file name and format, for example: F: / generateimage jpg * @return */ public static boolean GenerateImage(String imgStr, String imgFilePath) { // Base64 decodes the byte array string and generates a picture if (imgStr == null) // Image data is empty return false; Base64.Decoder decoder = Base64.getDecoder(); try { // Base64 decoding byte[] b = decoder.decode(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// Adjust exception data b[i] += 256; } } // Generate jpeg image OutputStream out = new FileOutputStream(imgFilePath);// Newly generated picture out.write(b); out.flush(); out.close(); System.out.println("Saved successfully" + imgFilePath); return true; } catch (Exception e) { System.out.println("Error " + e.getMessage()); return false; } } }
Python language API call
The AccessToken obtained earlier needs to be used
import urllib3,base64 import json from urllib.parse import urlencode # AccessToken obtained earlier access_token='' http=urllib3.PoolManager() url='https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token='+access_token f = open('F:/testimg/demo-card-2.jpg','rb') # Parameter image: base64 encoding of image img = base64.b64encode(f.read()) params={'image':img} # urlencode base64 data params=urlencode(params) request=http.request('POST', url, body=params, headers={'Content-Type':'application/x-www-form-urlencoded'}) # Process the returned byte. Python 3 outputs a bit string instead of a readable string, which needs to be converted result = str(request.data,'utf-8') # Using json library string to dictionary resultObject = json.loads(result) # Save as picture file imgByte = base64.b64decode(resultObject['image']) newFile = open('F:/testimg/demo-card-2110py.jpg','wb') newFile.write(imgByte) newFile.close()