首页 > 热点 > 微信 > 正文

微信小程序人脸识别功能代码实例

2024-07-22 01:18:34
字体:
来源:转载
供稿:网友

前几天偶然看见一个人脸识别的小程序demo,觉得很有趣下载下来想玩玩,结果只是一个框架而已用不了的,花了点时间完善一下

吐槽一下wx.uploadFile这个接口,真是个大坑,最开始调用时候,我以为它和同期的wx.downloadFile一样,只需要填入必须的参数就可以用,结果还是要配合后台php的

首先,upload这个接口的url和request一样指的是php的路径,而不是download一样文件路径

其次,我在最开始一直没弄懂这个"name"到底应该填什么,上传功能不好用我一直觉得是"name"的原因,官方对于name给的解释很迷,这里我就给个结论,大家不要纠结这个属性,直接写file就好,图片属性是能用的

最后,人脸识别功能的功能本身是第三方提供的,比如我用的就是阿里云的人脸识别功能,不到一分钱一张图片充值一块钱就可以玩的很嗨

那么,上代码,我的代码基本就是网上的demo+自己修改

首先是wxml

<view class="container"> <view class="userinfo">  <image class="userinfo-avatar" mode="aspectFit" src="{{tempFilePaths}}" background-size="cover"></image>  <text class="userinfo-tips">{{userInfo.tips}}</text> </view> <view class="usermotto"> <button class="button" type="primary" bindtap="chooseimage">{{motto}}</button> </view></view>

然后js代码

var app = getApp()Page({ data: {  motto: '上传靓照',  userInfo: {},  tempFilePaths: '' }, chooseimage: function () {  var that = this;  wx.chooseImage({   //选择图片   count: 1,   sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有   sourceType: ['album', 'camera'],    success: function (res) {    var tempFilePaths = res.tempFilePaths    that.setData({     tempFilePaths: tempFilePaths[0]    })    wx.uploadFile({   //上传图片     url: '', //这里是你php的路径!!     filePath: tempFilePaths[0],     name: 'file',     header: {      'content-type': 'multipart/form-data'     },     success: function (res) {      console.log("add success", res.data);      that.uploadImage(res.data);      wx.showToast({       title: "图片上传成功",       icon: 'success',       duration: 700      })     }    })   }  }) }, //事件处理函数 uploadImage: function(picName) {  var that = this  wx.showToast({   title: '鉴定中,请稍候',   icon: 'loading',   duration: 2000})   wx.request({    url: '',        //这里是阿里云人脸识别功能php的路径    data: {     type: 0,     image_url: picName,    },    header: {     'Content-Type': 'application/json'    },   // filePath: tempFilePaths[0],   name: 'file',   success: function(res){    console.log(res.data)     wx.hideToast()    var data = res.data;    var sex = data.gender;    const genders = {     'Male': '基佬',     'Female': '小仙女'    }      if(data.face_num == 0){     that.setData({      userInfo:{      tips:'未检测到人脸'      }     })     return    } else {     if (sex == 0) {      that.setData({       userInfo: {        tips: data.face_num + '位' + data.age + '岁的' + genders.Female       }      })     } else {      that.setData({       userInfo: {        tips: data.face_num + '位' + data.age + '岁的' + genders.Male       }      })     }     return    }     }  })  }, onLoad: function () {  console.log('onLoad');  }, onShareAppMessage: function () {   }})            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表