百度智能云在线活体检测

使用V3接口,接口文档详见百度智能云 https://cloud.baidu.com/doc/FACE/s/Zk37c1urr

活体检测工具类

package *.*.*.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;


/**
 * 活体检测工具类
 * @author sxxu
 *
 */
@Controller
@RequestMapping(value = "/",produces="text/html;charset=UTF-8;")
public class BDFaceVerify {
	
	public static final String APP_ID = "";
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";
	//接口地址
	public static String FACE_VERIFY ="https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
	
	/**
	 * 人脸在线活体检测示例代码
	 * @param param base64图片
	 * @return error_msg
	 */
	@ResponseBody
	@RequestMapping("/faceVerify")
	public String FaceVerify(@RequestBody String param,HttpServletRequest request,HttpServletResponse response) {
        try {
        	JSONObject json = GAParamUtil.validateParams(param);
    		if (json.isEmpty()) {
    			return GAParamUtil.FAIL(json).toString();
    		}
    		String image = GiantUtils.stringOf(json
    				.get("image"));
            Map<String, String> map = new HashMap<String, String>();
            map.put("image", image);
            map.put("image_type", "BASE64");
            map.put("face_field", "age,beauty,spoofing");
            map.put("option", "COMMON");
            List<Map<String, String>> list = new ArrayList<>();
            list.add(map);
            String params = JSON.toJSONString(list);
            System.out.println("======"+params);
            // 注意线上环境access_token有过期时间,此处为每次都重新请求
            // 获取accessToken
            String accessToken = getAuth();
            String result = HttpUtil.post(FACE_VERIFY, accessToken, params);
            JSONObject jsonObject = JSONObject.fromObject(result);
            String error_msg = jsonObject.getString("error_msg");
            return error_msg;
        	
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	/**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    private static String getAuth() {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + API_KEY
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + SECRET_KEY;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }
}

http工具类

package *.*.*.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}

前端页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
<script type="text/javascript" src="${staticPath}/static/html5/js/jquery.js"></script>
</head>

<body>
	<input id="checkflag" type="hidden" value="1">
	<div class="form-group" id="facecheck">
		<div style="text-align:center">
			<span style="font-size: 20px;color: red">请拍照进行活体检测</span>
		</div>
		<video id="video" class="video" style="width: 300px;height: 270px"
			controls> </video>
		<canvas id="canvas" width="300" height="230"
			style="float:right;margin-top:20px;"></canvas>
		<div style="text-align:center">
			<span id="capture" onclick="snap()" class="gainetbtn">拍照</span>
		</div>
		<div style="text-align:center">
			<span id="capture" onclick="getCompetence()" class="gainetbtn">打开摄像头照</span>
		</div>
		<div style="text-align:center">
			<span id="capture" onclick="stopNavigator()" class="gainetbtn">关闭摄像头</span>
		</div>
		<br>
		<div style="text-align:center">
			<span onclick="faceCheck()" class="gainetbtn">活体检测</span>
			<div style="font-size: 20px;color: red" align="center" id="result">
			</div>
			<input name="image" id="image" type="hidden" class="form-control"
				required>
		</div>
	</div>
</body>
<script type="text/javascript">
    $(function(){
    	showFace();
	});
	function IsPC() {
	    var userAgentInfo = navigator.userAgent;
	    var Agents = ["Android", "iPhone",
	                "SymbianOS", "Windows Phone",
	                "iPad", "iPod"];
	    var flag = true;
	    for (var v = 0; v < Agents.length; v++) {
	        if (userAgentInfo.indexOf(Agents[v]) > 0) {
	            flag = false;
	            break;
	        }
	    }
	    return flag;
	}
	
	var flag = IsPC(); //true为PC端,false为手机端
	
	var thisCancas;
	var thisContext;
	var thisVideo;

	// 调用权限(打开摄像头功能)
   function getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvas");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("video");
      //_this.thisVideo.style.display = 'block';
      // 获取媒体属性,旧版本浏览器可能不支持mediaDevices,我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices,我们不能只分配一个对象
      // 使用getUserMedia,因为它会覆盖现有的属性。
      // 这里,如果缺少getUserMedia属性,就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持,会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {//不存在则报错
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则,使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)"
        }
      };
      navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它,因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function(e) {
            _this.thisVideo.play();
          };
      }).catch(err=> {
          //console.log(err);
      });
    };

	// 打开新增信息对话框
    function showFace() {
    	$("#checkflag").val("-1");
		
		var canvas = document.getElementById('canvas');
        canvas.width = canvas.width
		$("#result").html("");
		getCompetence();
		
    }
	// 拍照
	function snap(){
	  	thisContext.drawImage(video, 0, 0, 300, 230);
        var imgData = thisCancas.toDataURL();
        $("#image").val(imgData);
	}
	
	// 关闭摄像头
    function stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    }
	
    var clear_time;
    // 人脸核验
    function faceCheck(){
	    var image=$("#image").val().split(",")[1];
	    var param = {};
		param["image"] = image;
		$.ajax({
             url: '<%=basePath%>/faceVerify',
             type: "post",
             dateType:"json",
             headers:{
		        	"Content-Type" : "application/json;charset=UTF-8"
		       },
             data: JSON.stringify(param),
             success: function (data) {
            	 $("#result").html(data);
             }
        });
    }

</script>
</html>

效果

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值