前端开启摄像头并拍照将照片的base64码传到后端

<div>
//登录弹出框
<el-form ref="form" :model="form" :rules="rules" :show-message="false">
   <el-form-item prop="username">
      <el-input v-model="form.username" class="inp" placeholder="请输入账号">
         <i slot="prefix" class="el-icon-user"></i>
      </el-input>
   </el-form-item>
   <el-form-item prop="password">
      <el-input v-model="form.password" class="inp" placeholder="请输入密码" show-password>
        <i slot="prefix" class="el-icon-lock" ></i>
      </el-input>
      </el-form-item>

   <el-form-item>
      <el-button type="primary" class="btn" @click="login">登录</el-button>
   </el-form-item>
</el-form>
//人脸验证弹出框
<el-dialog title="登录验证" :visible.sync="dialogFormVisible1" width="24%" height="50%" center>
      <el-form :model="form" >
        <div>
            <video v-if="xians"  id="video" width="300px" height="300px" autoplay="autoplay"></video>       
            <canvas hidden id="canvas" width="300px" height="300px"></canvas> 
        </div>
      <el-button id="snap" @click="takePhoto1()" type="primary">拍照验证</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
      </div>
</el-dialog>
</div>

<script>
methods: {
//登录验证事件
login(){
   this.$refs.form.validate((valid) => {
      if (valid) {
        this.dialogFormVisible1=true
        this.xians=true
        this.getMedia()
      } else {
        this.$message.error("请输入账号和密码")
        return false;
      }})      
},
//开启摄像头
getMedia() {
    let _this=this;
    let constraints = {
       video: { width: 500, height: 500 },
    };
    let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(function (MediaStream) {
        video.srcObject = MediaStream;
        _this.MediaStreamTrack=typeof MediaStream.stop==='function'?MediaStream:MediaStream.getTracks()[0];
        video.play();
        }).catch(function (PermissionDeniedError) {
                console.log(PermissionDeniedError);
        })
},
//拍照
async takePhoto1() {
    //获得Canvas对象
    let video = document.getElementById("video");
    let canvas = document.getElementById("canvas");
    let ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, 300, 400);
    var photoSrc = document.getElementById("canvas").toDataURL("image/jpeg", 0.8);
       var res=await this.http.post('/User/login',{
              'pic':photoSrc,
              'name':this.form.username,
              'password':this.form.password
       })
       if(res.data.code==200){
              sessionStorage.setItem("token",res.data.token)
              sessionStorage.setItem("user",this.form.username)
              this.$router.push("/home")
              this.$notify({
                title: '登录成功',
                message: '欢迎'+this.form.username+'登录',
                type: 'success'
       });  
                                          
       }else if(res.data.code==501){
              this.$message.error('请保证摄像头中有人脸!')
       }else if(res.data.code==500){
              this.$message.error('登录失败,请检查账号密码以及人脸是否正确')
       }
},
//关闭摄像头
cancalCloseVideo(){
  this.MediaStreamTrack && this.MediaStreamTrack.stop();
}
}
</script>

后端通过腾讯云接口进行验证

# 腾讯云注册(如果涉及到注册的逻辑的话)
def txregister(name,image):
    try:
        cred = credential.Credential("SecretId", "SecretKey")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-beijing", clientProfile)

        req = models.CreatePersonRequest()
        params = {
            "GroupId": "21072107",
            "PersonName": name,
            "PersonId": name,
            'Image':image
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreatePerson(req)
        return resp

    except TencentCloudSDKException as err:
        print(err)


# 腾讯云登录方法
def txlogin(name,image):
    try:
        cred = credential.Credential("SecretId", "SecretKey")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-beijing", clientProfile)

        req = models.VerifyFaceRequest()
        params = {
            'Image': image,
            "PersonId": name
        }
        req.from_json_string(json.dumps(params))
        encoded_jwt = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
        resp = client.VerifyFace(req)
        return resp
    except TencentCloudSDKException as err:
        print(err)
# 登录
def login(req):
    b = req.body.decode("utf-8")
    b = json.loads(b)
    str = b['pic'].split(",")[1]
    user = UserModel.objects.filter(username=b['name'], password=b['password']).values()
    if user:
        encoded_jwt = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
        res=txlogin(b['name'],str)
        print(res)
        if res.Score==100:
            return JsonResponse({"message": '登录成功', 'code': 200,'token': encoded_jwt})
        else:
            return JsonResponse({"message": '人脸验证失败', 'code': 501})
    else:
        return JsonResponse({"message": '请输入正确账号密码', 'code': 501})

因为我这里购买的是腾讯云人脸识别中人脸验证的接口,所以设计到人员库的使用,这里具体可以看腾讯云官方文档:人脸识别 获取人员库信息-API 文档-文档中心-腾讯云 (tencent.com)

 因为我这里直接使用的sdk生成代码来完成接口的使用,如果使用的话需要安装一下,具体可以看官方文档:Python-SDK 中心-腾讯云 (tencent.com)

pip install --upgrade tencentcloud-sdk-python
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐