如何在微信小程序中实现人脸识别功能

发布时间:2021-05-22 17:33:48 作者:Leah
来源:亿速云 阅读:837

本篇文章给大家分享的是有关如何在微信小程序中实现人脸识别功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

首先是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 () {
  
 }
})

最后上php

首先是阿里云人脸识别功能代码

<?php
$akId = "";
$akSecret = "";
$image_url = "";
//更新api信息
$url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute";
$content = array(      
	'type' => 0,
	'image_url' => $image_url
);
$options = array(
  'http' => array(
    'header' => array(
      'accept'=> "application/json",
      'content-type'=> "application/json",
      'date'=> gmdate("D, d M Y H:i:s \G\M\T"),
      'authorization' => ''
    ),
    'method' => "POST", //可以是 GET, POST, DELETE, PUT
    'content' => json_encode($content)//如有数据,请用json_encode()进行编码
  )
);
$http = $options['http'];
$header = $http['header'];
$urlObj = parse_url($url);
if(empty($urlObj["query"]))
  $path = $urlObj["path"];
else
  $path = $urlObj["path"]."?".$urlObj["query"];
$body = $http['content'];
if(empty($body))
  $bodymd5 = $body;
else
  $bodymd5 = base64_encode(md5($body,true));
$stringToSign = $http['method']."\n".$header['accept']."\n".$bodymd5."\n".$header['content-type']."\n".$header['date']."\n".$path;
$signature = base64_encode(
  hash_hmac(
    "sha1",
    $stringToSign,
    $akSecret, true));
$authHeader = "Dataplus "."$akId".":"."$signature";
$options['http']['header']['authorization'] = $authHeader;
$options['http']['header'] = implode(
  array_map(
    function($key, $val){
      return $key.":".$val."\r\n";
    },
    array_keys($options['http']['header']),
    $options['http']['header']));
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context );
echo($file);
?>

然后是后台图片上传服务器功能,这里的代码也是我参考大佬,然后自己修改的【侵删】

<?php
date_default_timezone_set("Asia/Suzhou"); //设置时区 
$code = $_FILES['file'];//获取小程序传来的图片 
if(is_uploaded_file($_FILES['file']['tmp_name'])) {  
  //把文件转存到你希望的目录(不要使用copy函数)  
  $uploaded_file=$_FILES['file']['tmp_name'];  
  $username = "image"; 
  //我们给每个用户动态的创建一个文件夹  
  $user_path=$_SERVER['DOCUMENT_ROOT']."/WeChatphp/".$username;  //  DOCUMENT_ROOT是你域名配置的根目录,后面的目录可自己调整
 
  //判断该用户文件夹是否已经有这个文件夹  
  if(!file_exists($user_path)) {  
    mkdir($user_path);  
  }  
  $file_true_name=$_FILES['file']['name'];  
	$move_to_file_1 = time().rand(1,1000)."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));
  $move_to_file=$user_path."/".$move_to_file_1;//strrops($file_true,".")查找“.”在字符串中最后一次出现的位置  
  if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {   
		echo $move_to_file_1;	
  } else {  
    echo "上传失败".date("Y-m-d H:i:sa");  
 
  }  
} else {  
  echo "上传失败".date("Y-m-d H:i:sa");  
}  
?>

以上就是如何在微信小程序中实现人脸识别功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. PHP制作微信小程序人脸识别功能
  2. 如何在微信小程序中实现一个搜索功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序

上一篇:使用JavaScript怎么实现一个框选功能

下一篇:如何在vue中使用element实现表单校验功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》