微信小程序人工智能之上传头像

微信小程序人工智能之上传头像_第1张图片

当用户选好照片后点击确定上传图片进入图库并和人像库进行对比

前台代码wxml


采集照片 {{student.name}}{{student.no}} 个人照片 {{imageList.length}}/1

前台是使用weui框架所以直接引用样式就可以了

js代码调用接口实现具体功能

// pages/headimg/headimg.js
//获取应用实例
const app = getApp()

//上传
function upload(that, id) {
  if (that.data.imageList.length == 0) {
    return;
  }
  wx.uploadFile({
    url: app.globalData.url.upload, //仅为示例,非真实的接口地址
    filePath: that.data.imageList[0],
    header: {
      Cookie: wx.getStorageSync('session_id')
    },
    name: 'file',
    formData: {
      'id': id
    },
    success: function (res) {
      var data = res.data
      console.log(data);
      // var json = JSON.parse(res.data);
      wx.showToast({
        title: data,
        icon: 'none',
        duration: 3000
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '../index/index',
        })
      }, 2000)
    }
  })
}

Page({
  data: {
    imageList: [],
    id: null,
    options: null
  },
  onLoad: function (options) {
    var id = options.id;
    console.log(options);
    this.setData({ options: options })
    this.setData({ id: options.id })
  },
  formSubmit: function (e) {
    upload(this, this.data.id);
    wx.navigateTo({
      url: '../list/list'
    })

  },

  chooseImage: function () {
    var that = this
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      count: 1,
      success: function (res) {
        console.log(res)
        that.setData({
          imageList: res.tempFilePaths
        })
      }
    })
  },
  previewImage: function (e) {
    // var current = e.target.dataset.src

    wx.previewImage({
      current: e.currentTarget.id,
      urls: this.data.imageList
    })
  },
  
})

具体调用的接口

首先是上传图片的接口

//上传图片
    public function upload($id=''){
        if(empty($id)){
            return false;
        }

        $no = M("student")->where("id={$id}")->getField('no');
        $dir = "./Uploads/studentface/";
        if(!file_exists($dir)){
            mkdir($dir, 0777, true);
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = $dir; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传(子)目录
        $upload->saveName = $no;
        $upload->replace = true;
        $upload->autoSub = false;
        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {// 上传错误提示错误信息
            // return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getError()));
            return json_encode(array('error'=>true,'msg'=>$upload->getError()),JSON_UNESCAPED_UNICODE);
        }else{// 上传成功 获取上传文件信息
            // return $this->ajaxReturn(array('error'=>false,'msg'=>$info['savepath'].$info['savename'],'id'=>$id));
            $file = $dir . $info['savepath'] . $info['savename'];
            $image = base64_encode(file_get_contents($file));
            $this->facevalid($no,$image);

            $m = M('head');
            $data = $m->where("no='{$no}'")->find();

            if($data){
                //有数据,则更新
                $m->where("no='{$no}'")->save(array('base64'=>$image, 'path'=>$file));
            }else{
            	$m->add(array('no'=>$no,'base64'=>$image,'path'=>$file));
            }

            return "采集照片成功";
        }
    }
private function face_group(){
    	$groupname = 'pingjiao';
    	$client = $this->init_face();
    	$ret = $client->getGroupList();
    	if($ret['error_code'] == 0){
    		$grouplist = $ret['result']['group_id_list'];
    		if(in_array($groupname, $grouplist)){
    			return $groupname;
    		}else{
    			$ret = $client->groupAdd($groupname);
    			if($ret['error_code'] == 0){
    				return $groupname;
    			}else{
    				return false;
    			}
    		}
    	}
    }	$groupname = 'pingjiao';
    	$client = $this->init_face();
    	$ret = $client->getGroupList();
    	if($ret['error_code'] == 0){
    		$grouplist = $ret['result']['group_id_list'];
    		if(in_array($groupname, $grouplist)){
    			return $groupname;
    		}else{
    			$ret = $client->groupAdd($groupname);
    			if($ret['error_code'] == 0){
    				return $groupname;
    			}else{
    				return false;
    			}
    		}
    	}
    }

 

public function facevalid($no,$image){

        $options = array();
        $options["face_field"] = "age";
        $options["max_face_num"] = 2;
        // $options["face_type"] = "LIVE";

        // 调用人脸检测
        $client = $this->init_face();
        // 带参数调用人脸检测
        $ret = $client->detect($image,'BASE64',$options);
        // print_r($ret);
        if($ret['error_code'] == 0){ //有人脸
        	$result = $ret['result'];
        	$face_num = $result['face_num'];

        	if(1 == $face_num){ //人脸数量为1
        		$face_probability = $result['face_list'][0]['face_probability'];
        		if(1 == $face_probability){ //可靠性为1
        			// $guid = myguid();
        			$group = $this->face_group();
                    $faces = $client->faceGetlist($no,$group);
                    if($faces['error_code']>0){
                        $client->addUser($image, 'BASE64', $group, $no);
                    }else{
                        $client->updateUser($image, 'BASE64', $group, $no);
                    }
        			
        			echo "人脸检测完成,并已入库";
                    return;
        		}else{
        			die('图片质量仅为:' . $face_probability . ',上传失败!');
        		}
        	}else{
        		die('人脸数量大于1,上传失败!');
        	}
        }else{
            die("没有人脸,上传失败!");
        }


    }

 

你可能感兴趣的:(微信小程序人工智能之上传头像)