前幾天偶然看見一個(gè)人臉識別的小程序demo,覺得很有趣下載下來想玩玩,結(jié)果只是一個(gè)框架而已用不了的,花了點(diǎn)時(shí)間完善一下
吐槽一下wx.uploadFile這個(gè)接口,真是個(gè)大坑,最開始調(diào)用時(shí)候,我以為它和同期的wx.downloadFile一樣,只需要填入必須的參數(shù)就可以用,結(jié)果還是要配合后臺php的
首先,upload這個(gè)接口的url和request一樣指的是php的路徑,而不是download一樣文件路徑
其次,我在最開始一直沒弄懂這個(gè)"name"到底應(yīng)該填什么,上傳功能不好用我一直覺得是"name"的原因,官方對于name給的解釋很迷,這里我就給個(gè)結(jié)論,大家不要糾結(jié)這個(gè)屬性,直接寫file就好,圖片屬性是能用的
最后,人臉識別功能的功能本身是第三方提供的,比如我用的就是阿里云的人臉識別功能,不到一分錢一張圖片充值一塊錢就可以玩的很嗨
那么,上代碼,我的代碼基本就是網(wǎng)上的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'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有 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 }) } }) } }) }, //事件處理函數(shù) 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)//如有數(shù)據(jù),請用json_encode()進(jìn)行編碼 ));$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);?>
然后是后臺圖片上傳服務(wù)器功能,這里的代碼也是我參考大佬,然后自己修改的【侵刪】
<?phpdate_default_timezone_set("Asia/Suzhou"); //設(shè)置時(shí)區(qū) $code = $_FILES['file'];//獲取小程序傳來的圖片 if(is_uploaded_file($_FILES['file']['tmp_name'])) { //把文件轉(zhuǎn)存到你希望的目錄(不要使用copy函數(shù)) $uploaded_file=$_FILES['file']['tmp_name']; $username = "image"; //我們給每個(gè)用戶動態(tài)的創(chuàng)建一個(gè)文件夾 $user_path=$_SERVER['DOCUMENT_ROOT']."/WeChatphp/".$username; // DOCUMENT_ROOT是你域名配置的根目錄,后面的目錄可自己調(diào)整 //判斷該用戶文件夾是否已經(jīng)有這個(gè)文件夾 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,".")查找“.”在字符串中最后一次出現(xiàn)的位置 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"); } ?>
人臉識別的功能就完成了,最后上效果圖,帥氣的我胡,打call
以上所述是小編給大家介紹的微信小程序人臉識別功能詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答