动手实现一个微信小程序

作者: 97690CE50CC872D | 来源:发表于2018-10-18 12:52 被阅读4次

    开发环境

    • 微信小程序开发者工具 v1.02.1809260
    • 调试基础库 2.0.4

    实现功能

    • 上传一张图片检测图片中的人脸展示人脸属性信息,如年龄、性别、表情、美丑打分等。

    接口

    • 接口用到的百度AI开放平台的人脸检测与属性分析
      接口文档

    实现步骤

    1. 本地选取一张图片
    2. 获取图片base64编码
    3. 获取百度开发api请求token
    4. 请求人脸检测接口

    效果图

    效果图.png

    python实现

    先用python把接口调试一下,测试调通

    # encoding:utf-8
    import base64
    import json
    import urllib
    import urllib.request
    from urllib import request
    
    def get_token(host):
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                       "Content-Type": "application/json"}
        req = request.Request(url=host, headers=header_dict)
        res = request.urlopen(req)
        res = res.read()
        res_json = json.loads(res.decode('utf-8'))
        print(res_json)
        return res_json["access_token"]
    
    '''
    进行post请求
    url:请求地址
    values:请求体
    '''
    def get_info_post_json_data(url, value):
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                       "Content-Type": "application/json"}
        req = request.Request(url=url, data=value, headers=header_dict)
        res = request.urlopen(req)
        res = res.read()
        return (res.decode('utf-8'))
    '''
    调用百度API,进行人脸探测
    imgPath: 图片地址
    access_token: 开发者token
    '''
    def getBaiduFaceTech(imgPath, access_token):
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        # 二进制方式打开图片文件
        f = open(imgPath, 'rb')
        # 图片转换成base64
        img = base64.b64encode(f.read())
        params = {"image": img, "image_type": "BASE64", "face_field": "age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type"}
        params = urllib.parse.urlencode(params).encode(encoding='utf-8')
        request_url = request_url + "?access_token=" + access_token
        # 调用post其请求方法
        face_info = get_info_post_json_data(request_url, params)
        # json字符串转为对象
        face_json = json.loads(face_info)
        if face_json["error_code"] != 0:
        # 如果没有发现人像,会返回为空
        elif face_json["result"]['face_num'] != 0:
            # 把想要的部分提取存入字典中
            result = face_json['result']['face_list'][0]
            print("分值:" + str(result['beauty']))
            print("年龄:" + str(result['age']))
            print("性别:" + result['gender']['type'] + "\n可能性:" + str(result['gender']['probability']))
            gender = result['gender']['type']
            age = str(result['age'])
            beauty = str(result['beauty'])
            probability = str(result['gender']['probability'])
            face_dict = {"gender": gender, "age": age, "probability": probability, "beauty": beauty}
            return face_dict
        '''
    
    if __name__ == '__main__':
        # client_id 为官网获取的AK, client_secret 为官网获取的SK
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】'
        token = get_token(host)
        # 调用百度人脸识别API
        face_dict = getBaiduFaceTech("face.jpg", token)
    

    步骤1:本地选取一张图片

    直接调用小程序wx.chooseImage(Object object)从本地相册选择图片或使用相机拍照
    https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

    wx.chooseImage({
          count: 1, // 默认9
          sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
          success: function(res) {
            // 返回选中照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths;
            _this.setData({
              img: tempFilePaths[0],
            });
          })
    

    步骤2:

    早期在微信小程序中将图片base64化需要借助微信原生的 wx.canvasGetImageData 得到图片的像素信息,再通过开源库UPNG将像素信息编码,最后通过wx.arrayBufferToBase64转化为base64数据,看起来就挺麻烦的,我使用的调试基础库2.0.4,小程序有新接口获取图片base64编码,wx.getFileSystemManager() 注意版本库要在1.9.9以后的版本才支持
    https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.getFileSystemManager.html

     wx.getFileSystemManager().readFile({
                filePath: _this.data.img, // 选择图片返回的相对路径
                encoding: 'base64', //编码格式
                success: res => {
                  // console.log('data:image/png;base64,' + res.data)
                  _this.setData({
                    base64: res.data,
                  })
                  //   }
                  // })
    

    步骤3:

    百度的api要求向API服务地址使用POST发送请求,必须在URL中带上参数access_token,没得办法要用人家的服务就得按规矩来,直接使用wx.request()发起一个网络请求
    https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

     wx.request({
          url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】',
          header: {
            'content-type': 'application/json'
          },
          method: "POST",
          success(res) {
            _this.setData({
              access_token: res.data.access_token,
            })
          }
        })
    

    步骤4:

    带上access_token和图片base64编码请求人脸检测接口,还是一个wx.request()发起一个网络请求
    https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

     wx.request({
                    url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect' + '?access_token=' + _this.data.access_token,
                    data: {
                      // image: _this.data.img,
                      image: _this.data.base64,
                      image_type: 'BASE64',
                      // image_type:'URL',
                      face_field: 'age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type',
                    },
                    header: {
                      'content-type': 'application/json'
                    },
                    method: "POST",
                    success(res) {
                      wx.hideLoading();
                      // console.log(res.data);
                      var data = res.data;
                    }
            })
    

    完整参考代码 weixinxiaochengxu

    参考链接

    微信小程序图片压缩及base64化上传
    小程序选择相册后转为base64编码的方法
    小程序图片转Base64,方法总结

    相关文章

      网友评论

        本文标题:动手实现一个微信小程序

        本文链接:https://www.haomeiwen.com/subject/mvyjzftx.html