百度AI人脸识别的学习总结

本文主要分以下几个模块进行总结分析

项目要求:运用百度AI(人脸识别)通过本地与外网之间的信息交互(MQService),从而通过刷脸实现登陆、签字、会议签到等;

1.准备工作:

  内网:单击事件按钮——签字、登陆

        qm.js(用于封装调用签名弹出页面的方法)

        sdkqz.jsp(用于签名模式的选取)

      getitems.jsp(用于jQuery的ajax调用)

         logininputbg.gif(用于人脸识别显示的动图--页面效果)

  步骤:1.用户单击按钮(以签字为例) onclick="signature('<%=map.get("COL_ID")%>','<%=user.getUserId() %>','QM','')" 

     2.调用signature()

      <script src="<%= path%>/js/qm.js"></script>

      //签名
      function signature(id, userid,lx,qzrq){
        var path = '<%=path%>';
        qm(path,id, userid,lx,qzrq);
      }

     3.进入qm.js中调用function通过ymPrompt打开sdkqz.jsp窗口

      qm.js中内容(略)

      sdkqz.jsp页面内容如下:  

        
 <%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.net.InetAddress"%>
<%@page import="org.daisy.daisyframework.control.ApplicationContext"%>
<%@page import="org.daisy.daisyframework.token.AccessTokenManager"%>
<%@page import="com.cwai.logic.bean.User"%>
<%@page import="com.cwai.logic.dao.UserDAO"%>
<%@page import="com.cwai.db.DBA"%>
<%@page import="org.daisy.daisyframework.commons.persistent.db.DataManipulation"%>
<%@page import="com.cwai.ado.XDataConvert"%>
<%@page import="com.cwai.xtag.xtag"%>
<%@page import="com.cwai.startup.AppConfigDb"%>
<%@page import="com.cwai.cfg.Configs"%>
<%@page import="com.cwai.web.App"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
if(null == session||session.getAttribute("LoginUser") == null){out.println("<script language='javascript'> function reLongin(){top.window.PAGE_FLAG = false;top.location = '"+path+"/fail.jsp?ID = 001'"+"}</script> ");out.println("<script language='javascript'> reLongin();</script> "); return; }
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
DataManipulation dataManipulation = (DataManipulation) ApplicationContext.getContext().getBean("dataManipulation");
String windowTitle = Configs.getWinTitle();
Object obj = session.getAttribute("rand_yzm"); String userId = xtag.getParameter(request, "userId");
String id = xtag.getParameter(request, "id").trim();
String lx = xtag.getParameter(request, "lx");
String qzrq = xtag.getParameter(request, "qzrq").trim();
String hqshow = xtag.getParameter(request, "qzrq"); AppConfigDb appConfig = AppConfigDb.getInstance();
String username = xtag.getParameter(request, "username_v");
username = username.trim();
String password = xtag.getParameter(request, "password_v");
//String mycode = xtag.getParameter(request, "code_v");
String logic = xtag.getParameter(request, "logic");
String login_result_js = "";
String code = "";
if(obj != null){
code = (String) obj;
}
boolean hasDbsx = false;
String dlip = App.GetIP(request); String qzzh = "";//签名账号
Map map_zh = dataManipulation.singleData("SELECT USERID,USERNAME,TRUENAME FROM BM_USER WHERE USERID = '"+userId+"' AND YXBZ = '1'", DBA.getConn(), new String[]{}, true);
qzzh = XDataConvert.TryToString(map_zh.get("USERNAME"));
String qzms = "";//签名模式
Map map_ms = dataManipulation.singleData("SELECT USERID,QZMS FROM BM_USER_INFO WHERE USERID = '"+userId+"'", DBA.getConn(), new String[]{}, true);
qzms = XDataConvert.TryToString(map_ms.get("QZMS"));
//System.out.println("qzms_____________"+qzms);
//获取用户电脑IP
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress().toString(); //1 混合验证(默认密码) 2混合验证(默认人脸识别) 3仅密码验证 4仅人脸识别验证
%> <!doctype html>
<html lang="us">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<!-- 强制360使用极速模式 -->
<meta name="renderer" content="webkit">
<base href="<%=basePath%>">
<title><%= windowTitle%></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<link href="<%= path%>/css/main.css" rel="stylesheet" type="text/css" />
<script src="<%= path%>/js/jquery-1.11.3.js"></script>
<script src="<%= path%>/js/layer/layer.js"></script>
<script type="text/javascript">
function enter(){
var url = '<%=basePath%>home.jsp';
var open_pattern = 2;
var w = screen.width + 8;
var h = screen.height + 7;
var l = 0;
var t = 0;
var window_style = "";
if(open_pattern == 1) {
t = -30;
l = -4;
window_style = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes";
var newwin = window.open(url, "_blank", window_style + ",width=" + w + ",height=" + h + ",top=" + t + ",left=" + l);
newwin.moveTo(l, t);
newwin.resizeTo(w, h);
window.opener = null;
window.close();
} else if(open_pattern == 2) {
window.location.href = url;
}
}
window.onload = function page_init() {
if('<%= qzms%>' == '' || '<%= qzms%>' == '1' || '<%= qzms%>' == '3'){
dlyz('1');
} else if ('<%= qzms%>' == '2' || '<%= qzms%>' == '4') {
dlyz('2');
}
showmsg();
if(!$("#username").is(":hidden")){
document.getElementById('username').focus();
}
}
function showmsg(){
<%=login_result_js%>
}
function refresh(obj) {
obj.src = "./code2.jsp?" + Math.random();
} </script>
<style type="text/css">
body {
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
font-family: Microsoft YaHei;
}
.cont{
width:400px;
height:350px;
border:0px;
} .contright {
align:center;
position: absolute;
width: 308px;
height: 300px;
right: 50px;
top: 10px;
border: 6px #D2E5F6 solid;
//background-color: #fff;
text-align: center;
background: url("<%= path%>/images/login/logininputbg.png") no-repeat;
} .mimas {
display: inline-block;
width: 13px;
} .yhdl {
margin-top: 25px;
font-size: 17px;
color: #666;
} .checkcolor {
color: #191970;
font-weight: bold;
} .logininput {
height: 25px;
font-size: 12px;
line-height: 25px;
border-left: 1px #C5DBEC solid;
border-top: 1px #C5DBEC solid;
border-bottom: 1px #C5DBEC solid;
border-right: 1px #C5DBEC solid;
padding-left: 5px;
outline: none;
} .tdleft {
font-size: 12px;
}
.zhdl {
width: calc(50% - 1px);
border-right: 1px solid #f4f4f4;
display: inline-block;
}
.rlsb {
display: inline-block;
width: calc(50% - 10px);
}
.login-btn .btn-img {
border: 1px solid #ff9f00;
display: block;
width: 244px;
background: #ff9f00;
height: 31px;
line-height: 31px;
color: #fff;
font-size: 20px;
font-family: 'Microsoft YaHei';
} .contright table td {
font-weight: bold;
color: #191970;
height:65px;
} .contright table tr {
height: 37px;
} .jy_a {
pointer-events : none;
} </style> </head>
<body style="background-color: #e9f3fd;margin: 0px;padding: 0px;">
<form action="" method="post" name="logonForm" id="logonForm">
<input type="hidden" name="username_v" id="username_v" value="">
<input type="hidden" name="password_v" id="password_v" value="">
<input type="hidden" name="code_v" id="code_v" value="">
<input type="hidden" name="logic" id="logic" value=""> <div id="div1" class="cont">
<div class="contright" style="">
<div class="yhdl" >
<%if("1".equals(qzms) || "2".equals(qzms)){ %>
<div class="zhdl" >
<span id="zhdl_span" style="cursor: pointer;" onclick="dlyz('1')">密&nbsp;码&nbsp;签&nbsp;字</span>
</div>
<div class="rlsb" >
<span id="rlsb_span" style="cursor: pointer;" onclick="dlyz('2')">面&nbsp;部&nbsp;识&nbsp;别</span>
</div>
<%}else if("3".equals(qzms)){ %>
<div class="zhdl" >
<span id="zhdl_span" style="cursor: pointer;" onclick="dlyz('1')">密&nbsp;码&nbsp;签&nbsp;字</span>
</div>
<%}else if("4".equals(qzms)){ %>
<div class="rlsb" >
<span id="rlsb_span" style="cursor: pointer;" onclick="dlyz('2')">面&nbsp;部&nbsp;识&nbsp;别</span>
</div>
<%} %>
</div> <div style="min-height: 210px;" align="center">
<div id="zhdl_div">
<br>
<br>
<table style="">
<tr>
<td class="tdleft">签&nbsp;字&nbsp;账&nbsp;号:</td>
<td>
<input id="username" name="username" maxlength="30" placeholder="用户名" type="text" style="width: 188px;" disabled="disabled" class="logininput" value="<%= qzzh%>">
</td>
</tr>
<tr>
<td class="tdleft">签&nbsp;字&nbsp;密&nbsp;码:</td>
<td>
<input id="password" name="password" maxlength="30" placeholder="密码" type="password" style="width: 188px;" class="logininput" onkeydown="if(event.keyCode==13) login()">
</td>
</tr>
</table>
</div>
<div id="rlsb_div" style="height: 210px;">
<br>
<img src="<%= path%>/images/login/logininputbg.gif" width="155px" height="155px" />
<br>
<a style="color: #666;">签&nbsp;字&nbsp;账&nbsp;号: <span style="font-weight: bold;font-size: 12px;color:#191970;" id="qzzh"><%= qzzh%></span></a>
<%--
<a id="qhzh_a" style="float: right; margin-right: 31px;color:#191970;cursor: pointer;font-weight: bold;" onclick="qhzh()">切换账号</a>
--%>
</div>
</div>
<div class="login-btn" align="center">
<a href="javascript:sendreq();" id="dl_a" class="btn-img">
确&nbsp;&nbsp;&nbsp;&nbsp;认<span id="fsqq"></span>
</a>
</div>
</div>
</div>
</form> <script type="text/javascript">
$(function(){
divcenter();
}) $(window).resize(function () { //当浏览器大小变化时
divcenter();
}); function divcenter(){
var left = $(window).width()/2 - 474;
var top = $(window).height()/2 - 272;
$("#div1").css('margin-top',top+'px');
$("#div1").css('margin-left',left+'px');
} function dlyz(lx) {
if(lx == '1') {
$("#zhdl_div").show();
$("#rlsb_div").hide();
$("#zhdl_span").addClass("checkcolor");
$("#rlsb_span").removeClass("checkcolor");
} else {
$("#rlsb_div").show();
$("#zhdl_div").hide();
$("#rlsb_span").addClass("checkcolor");
$("#zhdl_span").removeClass("checkcolor");
}
} var v_str = '用户名:&nbsp;&nbsp; <input type="text" id="lrxzh" name="lrxzh" placeholder="用户账号"/>';
function zhlr(){
layer.open({
title: '账号录入',
content: v_str,
btn: '确定',
yes: function(index){
if($("#lrxzh").val() != ''){
$("#dqdlzh").html($("#lrxzh").val());
layer.close(index);
}
}
});
} function sendreq() {
if($("#zhdl_div").is(":hidden")) {// 人脸识别校验
sendMsg();
} else {//密码签字校验
dzqm();
}
} var id = '<%=id%>';
var userid = '<%=userId%>';
//用于签名时间(FORM_20170117050524000077.jsp)
var qzrq = '<%=qzrq%>';
var ny = '<%= new SimpleDateFormat("yyyy-MM-dd").format(new Date())%>';
var hqshow = '<%=hqshow%>';
//电子签名
function dzqm(){
var pass = document.getElementById("password").value;
$.ajax({
type: "POST",
url: "<%=path%>/ajax/formdata.jsp",
data: {type: 'SIGNATURE',userid: userid,pass: pass},
dataType: "json",
success:function(data){
console.log(data);
if(data.code == 2){
if("QM" == "<%=lx%>"){
var src = "<%=path%>/work/common/view_image2.jsp?tpid=" + data.qzxxid;
window.parent.$("#"+id+"_img").attr("src",src);
window.parent.$("#"+id).val(data.qzxxid);
window.parent.$("#"+id+"_btn").hide();
window.parent.$("#"+id+"_img").show();
if("" != qzrq && null != qzrq ){
window.parent.$("#"+qzrq).val(ny);
}
}else if("HQ" == "<%=lx%>"){
window.parent.app.huiqian.push({
userid: userid,
imgid: data.qzxxid
});
if("0" == hqshow){
window.parent.app.hqshow = false;
}else {
window.parent.$("#"+id+"_btn").hide();
}
}
window.parent.ymPrompt.close();
}else{
layer.msg(data.msg, {icon: 2, time: 8000});
}
}
});
}
//人脸识别签名
function sendMsg() {//30秒请求时间间隔
//1: 获取方式 2:账号信息 3:发送异步请求[a.获取登陆模式 b.等待数据返还]
var id = '<%=id%>';
if($("#qzzh").text() == '') {//当前登陆账号为空
zhlr();
} else {//有数据, 开始发送请求ajax请求
time($("#dl_a"));
$.ajax ({
url : '<%=path%>/ajax/getitems.jsp',
type: 'POST',
dataType : 'text',
async: true,
data : {"DMZL":"CHKSDK2", "queryValue": "<%= ip%>~<%= userId%>"},
success: function(data) {
if(data.trim() == '0'){
layer.msg("人脸识别信息发送失败!",{icon: 2, time: 3000});
} else {
layer.msg("人脸识别信息已发送,请于一分钟内登陆钉钉验证!",{time:5000});
var interval = setInterval(
function sdkLogin(){
console.log("请求数据来了————————————");
if(null != data && "" != data){
$.ajax({
url : 'ajax/getitems.jsp',
type : 'POST',
dataType : 'text',
data : {"DMZL":"CHKSDK_MSG", "queryValue": data },
success : function(back){
if(back.trim() == '2'){
layer.msg("该签名信息已经过时,请重新发送申请!",{icon: 2, time: 100000});
clearInterval(interval);
} else if(back.trim() == '3'){
//layer.msg("您已取消该签名信息!",{icon: 2, time: 3000});
clearInterval(interval);
} else if(back.trim() == '4'){
//获取qzxxid
$.ajax({
url : 'ajax/getitems.jsp',
type : 'POST',
dataType : 'text',
data : {"DMZL":"GETQZXXID", "queryValue": '<%= userId%>' },
success : function(qzxx){
//进行图片签字,显示图片
if("0" == qzxx.trim()){
layer.msg("没有被应用的签字,请先设置签字!",{icon: 2, time: 3000});
//停止时间函数
clearInterval(interval);
window.parent.ymPrompt.close();
}else{
if("QM" == "<%=lx%>"){
var src = "<%=path%>/work/common/view_image2.jsp?tpid=" + qzxx.trim();
window.parent.$("#"+id+"_img").attr("src",src);
window.parent.$("#"+id).val(qzxx.trim());
window.parent.$("#"+id+"_btn").hide();
window.parent.$("#"+id+"_img").show();
if("" != qzrq && null != qzrq ){
window.parent.$("#"+qzrq).val(ny);
}
}else if("HQ" == "<%=lx%>"){
window.parent.app.huiqian.push({
userid: userid,
imgid: qzxx.trim()
});
if("0" == hqshow){
window.parent.app.hqshow = false;
}else {
window.parent.$("#"+id+"_btn").hide();
}
}
//停止时间函数
clearInterval(interval);
window.parent.ymPrompt.close();
} }
});
} else if(back.trim() == '0'){
//layer.msg("人脸识别信息已发送,请于一分钟内登陆叮叮验证!",{time:1000});
}
}
});
}
}
, 1000);
} }
});
}
} var wait = 30;
function time(o) {
if (wait == 0) {
o.removeClass("jy_a");  
$("#qhzh_a").removeClass("jy_a");
   $("#fsqq").text('');
   wait = 30;
} else {
o.addClass("jy_a");
$("#qhzh_a").addClass("jy_a");
   $("#fsqq").text('('+ wait +')');
   wait--;
   setTimeout(function() {
time(o);
   },
   1000)
}
} function setWait(time){
if(time != null){
wait = time;
}
} function qhzh() {//切换账号
zhlr();
}
</script>
</body>
</html>

sdkqz.jsp

     4.sdkqz.jsp中通过ajax调用getitems.jsp获取相应的数据

      5.getitems.jsp中内容   

        
 <%@page import="org.daisy.daisyframework.commons.date.DateConvertor"%>
<%@page import="org.daisy.daisyframework.util.Xtag"%>
<%@page import="com.cwai.xtag.xtag"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%@page import="com.cwai.pass.Md5"%>
<%@page import="com.cwai.logic.bean.User"%>
<%@page import="org.daisy.daisyframework.util.DataConvertor"%>
<%@page import="org.daisy.daisyframework.commons.persistent.db.PrimaryKeyDependent"%>
<%@page import="com.cwai.db.DBA"%>
<%@page import="org.daisy.daisyframework.commons.persistent.db.DataManipulation"%>
<%@ page language="java" import="java.util.*,com.cwai.bean.*,com.cwai.xbean.*,com.cwai.ado.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath(); if(null==session||session.getAttribute("LoginUser")==null){out.println("<script language='javascript'> function reLongin(){top.window.PAGE_FLAG = false;top.location='"+path+"/fail.jsp?ID=001'"+"}</script> ");out.println("<script language='javascript'> reLongin();</script> ");return;}
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
User user = (User) session.getAttribute("LoginUser");
%>
<%
//代码种类
String dmzl = request.getParameter("DMZL") == null ? "" : request.getParameter("DMZL").toUpperCase();
//查询代码
String v = request.getParameter("queryValue") == null ? "" : request.getParameter("queryValue");
try{
if("GETQZXXID".equals(dmzl)){//根据userid获取签字信息ID
BaseDAO dao = new BaseDAO();
String qzxxid = dao.getValue("SELECT QZXX_ID FROM BM_USER_DZQZ T WHERE USERID = '"+v.trim()+"' AND SFYY = 1 AND DQYX = 1", new Object[]{});
System.out.println("map:"+qzxxid);
if("".equals(qzxxid) || null == qzxxid){
out.println("0");
}else{
out.println(qzxxid.trim());
}
}else if("CHKSDK_MSG".equals(dmzl)){//定时读取数据库SDK比对结果信息
DataManipulation dataManipulation = new DataManipulation();
String dd_sdksql = "SELECT ID, USERID, CONTENT, STATUS, IP, LX FROM DD_SDKMESSAGE WHERE ID = '"+v.trim()+"' ";
Map map = dataManipulation.singleData(dd_sdksql, DBA.getConn(),new String[]{}, true);
//System.out.println("map:"+map);
out.println(XDataConvert.TryToString(map.get("STATUS"))); }else if("CHKSDK2".equals(dmzl)){//创建一条即将比对的人脸比对信息
DataManipulation dataManipulation = new DataManipulation();
//System.out.println("flag::_____");
//更新表中已经存在大于30秒小于一分钟的数据
String dd_sdksql = "UPDATE DD_SDKMESSAGE SET STATUS = '3' , FINISH_TIME = SYSDATE WHERE STATUS = '0' AND USERID = '"+v.split("~")[1]+"'";
//System.out.println("dd_sdksql:"+dd_sdksql);
boolean f = dataManipulation.execute(dd_sdksql,DBA.getConn(),new String[]{}, true);
String xx_id = PrimaryKeyDependent.getDateRandomKey();
String content = "您收到一条新的签字(人脸识别)提醒,请于一分钟内进行验证!";
String dd_sdk = "INSERT INTO DD_SDKMESSAGE(ID, USERID, CONTENT, STATUS, IP, LX) "
+ " SELECT '"+ xx_id +"', '"+ v.split("~")[1] +"', '"+ content +"', '0', '" + v.split("~")[0] +"', '0' FROM DUAL WHERE 1 = 1 ";
//System.out.println("dd_sdksql:"+dd_sdksql);
boolean flag = dataManipulation.execute(dd_sdk, DBA.getConn(),new String[]{}, true);
//System.out.println("flag::_____"+flag);
if(flag){
out.println(xx_id);
}else{
out.println("0");
}

getitems.jsp

     6.定时获取数据库中信息,查看处理情况

  外网(手机端钉钉):

    分两种模式,模式1:打开钉钉直接进行面部比对;模式2:打开钉钉消息,进入主页面,通过单击按钮,进行签字(电子签名、面部识别)

    JAVA代码:

      AuthService.java(获取百度AI的token类)

      Base64ImageUtils.java(本地或者网络图片资源转为Base64字符串 )

      FileUtil.java(文件读取工具类)

 package com.cwai.service.dd;

 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 org.json.JSONObject; import com.cwai.cfg.Configs; /**
* 获取token类
*/
public class AuthService { /**
* 获取权限token
* @return 返回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public static String getAuth() { //String[] pro = FileUtil.getPro().split("~");//已不再使用
// 官网获取的 API Key 更新为你注册的
String clientId = Configs.BAIDU_AI_API_KEY; //百度云应用的AK
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = Configs.BAIDU_AI_SECRET_KEY; //百度云应用的SK
return getAuth(clientId, clientSecret);
} /**
* 获取API访问token
* 该token有一定的有效期,需要自行管理,当失效时需重新获取.
* @param ak - 百度云官网获取的 API Key
* @param sk - 百度云官网获取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public static String getAuth(String ak, String sk) {
// 获取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=" + ak
// 3. 官网获取的 Secret Key
+ "&client_secret=" + sk;
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));
}
System.err.println("getAccessTokenUrl:" + getAccessTokenUrl);
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.err.println("result1:" + getAccessTokenUrl);
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
System.err.println("result:" + result);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
} }

AuthService

Base64ImageUtils
FileUtil
 package com.cwai.util;

 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; /**
*
* 本地或者网络图片资源转为Base64字符串
*/
public class Base64ImageUtils {
/**
* @Title: GetImageStrFromUrl
* @Description: 将一张网络图片转化成Base64字符串
* @param imgURL 网络资源位置
* @return Base64字符串
*/
public static String GetImageStrFromUrl(String imgURL) {
byte[] data = null;
try {
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
data = new byte[inStream.available()];
inStream.read(data);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
} /**
* @Title: GetImageStrFromPath
* @Description: (将一张本地图片转化成Base64字符串)
* @param imgPath
* @return
*/
public static String GetImageStrFromPath(String imgPath) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
} /**
* @Title: GenerateImage
* @Description: base64字符串转化成图片
* @param imgStr
* @param imgFilePath 图片文件名,如“E:/tmp.jpg”
* @return
*/
public static boolean saveImage(String imgStr,String imgFilePath) {
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}

      HttpUtil.java(http 工具类)

      PropertiesUtil.java(.properties文件内容获取——本项目未使用直接调用类中的常量

      SDKMatch.java(图片比对——本项目只是针对两张图片进行比较,如果需要则可根据下方逻辑进行实现)

      SQLUtils.java(SQL类不做解释)

      AutoSendSDKMessage.java(实时获取数据库新建的信息,并处理-给用户发送钉钉消息)

 package com.cwai.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 generalUrl = requestUrl + "?access_token=" + accessToken;
System.out.println("generalUrl:" + generalUrl);
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true); // 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close(); // 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
if (requestUrl.contains("nlp"))
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
else
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.out.println("result:" + result);
return result;
}
}

HttpUtil

 package com.cwai.util;

 import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties; public class PropertiesUtil {
public static Properties prop = new Properties();
/**
* 取出值
* @param k
* @param filepath
* @return
*/
public static String getValue(String k, String filepath){
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream(filepath));
prop.load(in); ///加载属性列表
Iterator<String> it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
if (key.equals(k)){
return prop.getProperty(key);
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 设置键值
* @param filepath
* @param map
*/
public static void setValue(String filepath, Map<String, String> map){
///保存属性到b.properties文件
FileOutputStream oFile ;
try {
System.out.println("s"+filepath);
oFile = new FileOutputStream(filepath, false);
//true表示追加打开
System.out.println(map.get("key")+",,,"+map.get("value"));
prop.setProperty(map.get("key"), map.get("value"));
//prop.put(map.get("key"), map.get("value"));
prop.store(oFile, "The New properties file");
oFile.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}

PropertiesUtil

 package com.cwai.util;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.json.JSONObject; import com.baidu.aip.face.AipFace;
import com.baidu.aip.http.AipRequest;
import com.cwai.ado.XDataConvert;
import com.cwai.cfg.Configs;
import com.cwai.dao.DBManager; public class SDKMatch { /**
* 作用:进行人脸识别比对(手机端拍照图片与数据库中图片比较)获取结果
* @param url 网上文件地址
* @return 返回是否登录结果
* @throws Exception
*/
public static String faceCompare(String url,String userID) throws Exception{
// /zczhgzpt_out/src/config/SDK.properties
//String[] pro = FileUtil.getPro().split("~");
//初始化一个FaceClient
AipFace face = new AipFace(Configs.BAIDU_AI_API_APP_ID, Configs.BAIDU_AI_API_KEY, Configs.BAIDU_AI_SECRET_KEY);
System.out.println("APP_ID_____________________________-"+Configs.BAIDU_AI_API_APP_ID);
System.out.println("API_KEY_____________________________-"+Configs.BAIDU_AI_API_KEY);
System.out.println("SECRET_KEY_____________________________-"+Configs.BAIDU_AI_SECRET_KEY);
//可选:设置网络连接参数
face.setConnectionTimeoutInMillis(60000);
face.setSocketTimeoutInMillis(60000);
//调用API
HashMap map = new HashMap();
//所选属性,根据项目要求进行选择
map.put("ext_fields", "qualities");
//对第一张图片(线上拍照图片)进行活体检测
map.put("image_liveness", "faceliveness,");
map.put("types", "7,13");
//方式1
//使用图片地址 //方式2 //获取数据库数据
List list = SQLUtils.getPhotoList(userID);
System.out.println("list__________________________________________:"+list);
byte[][] images = new byte[list.size()+1][] ;
//获取网上图片内容
byte[] image0 = FileUtil.loadByteFromURL(url);
images[0] = image0;
if(list.size() > 0 && list != null){
for(int i=0;i<list.size();i++){
HashMap map_sj = (HashMap) list.get(i);
String userId = XDataConvert.TryToString(map_sj.get("USERID"));
String tpid = XDataConvert.TryToString(map_sj.get("TPID"));
byte[] image = new DBManager().getBlob("SELECT PHOTO FROM USER_PHOTO P WHERE USERID = '"+userId+"' AND TPID = '"+tpid+"'", new String[]{});
images[i+1] = image;
}
AipRequest aipRequest = new AipRequest();
aipRequest.setBody(map);
JSONObject obj = face.match(images, map);
String result = SDKMatch.compareResult(obj);
System.out.println("result_______________________________________:"+result);
return SDKMatch.resultAnalysis(result);
}else{
return "MAP_NO";
} }
/**
* 作用:对图片进行比对得到结果
* @param obj 比对后的JSON串
* @return
* @throws Exception
*/
public static String compareResult(JSONObject obj ) throws Exception{
String result = ""; String re = obj.get("result").toString();
String l = re.substring(1, re.length()-1).replace("},{", "}@{");
if(!"".equals(l.trim()) && l != null ){
Object[] str = l.trim().split("@");
List<Object> list = Arrays.asList(str);
int index_j = 0;
int index_i = 0;
double maxlik = 0.00;
for(int i=0; i<list.size();i++){
String ll = list.get(i).toString();//获取当前比较项的数据(String)
//Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");//StringToMap转换方式
String p = ll.replace("}", "");
p = p.replace("{", "");
p = p.replace("\"", "");
System.out.println("结果串:___________________________"+p);
String[] split = p.split(",");
String[] score = split[2].split(":");
String[] in_j = split[0].split(":");
String[] in_i = split[1].split(":");
double lik = Double.parseDouble(XDataConvert.TryToString(score[1]));
if(lik >= maxlik && ("0".equals(in_j[1]) || "0".equals(in_i[1]))){ //仅查询与人脸识别图片(第一张图片,即登陆图片)作比较的选项
maxlik = lik;
index_j = Integer.parseInt(XDataConvert.TryToString(in_j[1]));
index_i = Integer.parseInt(XDataConvert.TryToString(in_i[1]));
}
}
result = index_j+","+index_i+","+maxlik;
}else{
result = "0,0,0";
} //获取活体值
String ext_info = obj.get("ext_info").toString();
Map map_info = FileUtil.string2Map(ext_info);
String faceliveness=(String) map_info.get("faceliveness");
System.out.println("faceliveness的值为:______________________________-"+faceliveness);
result = result + "," + faceliveness; return result;
} /**
* 作用:用于得分设定(控制阀阀值)
* @param result
* @return
*/
public static String resultAnalysis(String result){
String[] r = result.split(",");
//System.out.println("r3:------------------------------"+r[3]);
if(!"0".equals(r[2]) && !"".equals(r[3])){
double score = Double.parseDouble(r[2]);
double liveness = Double.parseDouble(r[3]);//获取第一张图片的活体比对得分数
if(score >=80 && score <= 100 ){
if(liveness < 0.393241){//活体判断
return "LIVE_NO";
}else{
return "OK";
}
}
return "NO";
}else{
return "FACE_NO";
}
}
}

SDKMatch

 package com.cwai.util;

 import java.util.List;
import java.util.Map; import com.cwai.dao.DBManager;
public class SQLUtils {
public static List getPhotoList(String userId) throws Exception{
//数据库直连方式
// String DriverName="oracle.jdbc.driver.OracleDriver";
// String DBname="jdbc:oracle:thin:@118.190.95.111:1521:cwai"; //jdbc:oracle:thin:@计算机名:1521:数据库实例名
// String DBuser="zczhgzpt";
// String DBcode="oracle";
List list = null;
try {
String sql = "SELECT USERID,SCSJ,ZTX,TPID FROM USER_PHOTO WHERE ZTX = '1' AND USERID = '"+userId+"' ";//ZTX = '1' and
System.out.println(sql);
list = new DBManager().list(sql,new String[]{});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 作用:用于判断当前比对的信息情况
* @param userId
* @return
* @throws Exception
*/
public static Map getSDKMessageMap(String ID) throws Exception{
Map map = null;
try {
String sql = "SELECT ID,USERID,STATUS FROM DD_SDKMESSAGE WHERE ID = '"+ID+"' ";
map = new DBManager().singleData(sql,new String[]{});
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}

SQLUtils

 package com.cwai.startup;

 import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.daisy.daisyframework.mobile.dd.message.MsgResponse;
import org.json.JSONArray;
import org.json.JSONObject; import com.cwai.ado.XDataConvert;
import com.cwai.cfg.Configs;
import com.cwai.dao.DBManager;
/**
* 作用:通过百度AI进行线上人脸识别,比对,该文件用于获取数据库中发送的消息并给接收者发送叮叮消息
* @author wsf
* 20180423
*/
public class AutoSendSDKMessage implements Runnable { public void execute(){ try {
sendDDMessage();
} catch (Exception e) {
e.printStackTrace();
System.out.println("========================定时发送钉钉消息失败!");
}
}
private String min = "ROUND(TO_NUMBER(SYSDATE - CREATE_TIME)*1440)";
private String sec = "ROUND(TO_NUMBER(SYSDATE - CREATE_TIME)*86400)"; private void sendDDMessage() throws Exception{
String sql = "SELECT * FROM (SELECT "
+ "T.ID,T.USERID,T.STATUS,TO_CHAR(T.CREATE_TIME, 'YYYY-MM-DD HH24:MI:SS') CREATE_TIME,T.FINISH_TIME,T.IP,T.LX,T.CONTENT,B.USERID_DDPT "
+ "FROM DD_SDKMESSAGE T "
+ "JOIN BM_USER B ON B.USERID = T.USERID "
+ "WHERE STATUS = '0' AND DDSFFS = '0' AND "+sec+" < 50 ORDER BY T.CREATE_TIME "
+ ") WHERE ROWNUM < 15"; List list = DBManager.list(sql, new String[]{});
String ids = "";
Date date_before = new Date();
//System.out.println("---------------------");
//System.out.println("---------------------");
//System.out.println("---------------------");
System.out.println("准备发送钉钉消息..." + date_before.toLocaleString());
List sql_list = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
Map map = (HashMap)list.get(i);
if(!"".equals(map.get("USERID"))) {
JSONArray json=new JSONArray();
JSONObject json1 = new JSONObject();
json1.put("key", "[验证IP]:");
json1.put("value", XDataConvert.TryToString(map.get("IP")));
json.put(json1); String lx = XDataConvert.TryToString(map.get("LX"));
String lx_mc = "签名人脸识别";
if("1".equals(lx)){
lx_mc = "系统登录人脸识别";
}else if("2".equals(lx)){
lx_mc = "会议签到人脸识别";
}
JSONObject json2 = new JSONObject();
json2.put("key", "[验证类型]:");
json2.put("value", lx_mc);
json.put(json2); String create_time = XDataConvert.TryToDateTimeString(map.get("CREATE_TIME"));
JSONObject json3 = new JSONObject();
json3.put("key", "[申请时间]:");
json3.put("value", create_time);
json.put(json3); JSONObject json4 = new JSONObject();
json4.put("key", "[消息提醒]:");
json4.put("value", "请首先确认是否您本人发起,如非本人,您的身份可能正在被冒用,否则,请点击本消息完成验证。");
json.put(json4);
String check_url = Configs.getWww_location() + "work/common/sdk_xxpd.jsp?userid=" + XDataConvert.TryToString(map.get("USERID")) + "&ip=" + XDataConvert.TryToString(map.get("IP")) + "&createtime=" + (create_time.replace(" ", "").replace(":", "").replace("-", "")) + "&lx=" + lx + "&id=" + XDataConvert.TryToString(map.get("ID")) ;
//System.out.println("check_url_____________________________________________________"+check_url);
MsgResponse.sendOAMsg("ding41243d806b31cad2",XDataConvert.TryToString(map.get("USERID_DDPT")), "", Configs.getAgentid(), check_url, "面部识别验证提醒", json, "@lADOADmaWMzazQKA","");
System.out.println("--发送完毕:" + XDataConvert.TryToString(map.get("USERID")));
}
ids += map.get("ID") + ",";
}
//修改消息的发送状态
String sql_xxfs = "UPDATE DD_SDKMESSAGE SET DDSFFS = '1' WHERE ID IN ("+XDataConvert.toSqlInValues(ids)+")";//此处只是用来作为已发送的参照
sql_list.add(sql_xxfs);
//修改未进行验证已超时的信息状态(其中状态1,5的情况不作处理)
String sql_2 = "UPDATE DD_SDKMESSAGE SET STATUS = '2' WHERE STATUS = '0' AND FINISH_TIME IS NULL AND ROUND(TO_NUMBER(SYSDATE - CREATE_TIME)*1440) > 1 ";
sql_list.add(sql_2); //查询要删除的信息 String sql_insert = "INSERT INTO DD_SDKMESSAGE_LOG (ID,USERID,STATUS,CREATE_TIME,FINISH_TIME,IP,LX,DDSFFS) "
+ " select ID,USERID,STATUS,CREATE_TIME,FINISH_TIME,IP,LX,DDSFFS from DD_SDKMESSAGE where STATUS <> '0' AND "+min+" > 10 ";
sql_list.add(sql_insert); //删除大于十分钟的信息
String sql_del = "DELETE FROM DD_SDKMESSAGE WHERE STATUS <> '0' AND "+min+" > 10 ";
sql_list.add(sql_del); boolean flag = DBManager.executeBatch(sql_list); System.out.println("--------消息更新发送--------"+flag);
Date date_end = new Date();
System.out.println("发送钉钉消息完毕..." + date_end.toLocaleString() + "-----" + "本次用时:" + ((date_end.getTime() - date_before.getTime()) / 1000) + "秒");
} public void init() {
AutoSendSDKMessage service = new AutoSendSDKMessage();
Thread thread = new Thread(service);
thread.start();
} public void run() {
while (true){
try{
execute();
Thread.currentThread().sleep(4000);
} catch(Exception e) {
e.printStackTrace();
return;
}
}
}
}

AutoSendSDKMessage

    JSP、JS文件:

      sdk_xxpd.jsp 

      camera.jsp 

      camera_out.jsp  

      getitems.jsp(用于jQuery的ajax调用)  

      单击事件按钮——签字、登陆

         qm.js(用于封装调用签名弹出页面的方法)

    步骤1(模式1):

      1.AutoSendSDKMessage.java实时读取、发送消息到钉钉,

      2.打开钉钉消息,进入sdk_xxpd.jsp页面,对当前打开的信息进行判断

 <%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.cwai.util.SQLUtils"%>
<%@page import="com.cwai.dao.DBManager"%>
<%@page import="com.cwai.pass.Md5"%>
<%@page import="com.cwai.pass.Security"%>
<%@page import="java.io.OutputStream"%>
<%@page import="org.daisy.daisyframework.commons.persistent.db.PrimaryKeyDependent"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.daisy.daisyframework.commons.io.upload.apacheupload.ApacheUploadRequest"%>
<%@ page language="java" import="java.util.*,com.cwai.xtag.*,com.cwai.web.*,com.cwai.ado.*,com.cwai.bean.*,com.cwai.xbean.*" pageEncoding="UTF-8"%>
<%@page import="com.cwai.logic.bean.User"%>
<jsp:directive.page import="com.cwai.ado.XDataConvert"/>
<jsp:directive.page import="org.daisy.daisyframework.commons.persistent.db.DataManipulation"/>
<jsp:directive.page import="org.daisy.daisyframework.control.ApplicationContext"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+ request.getServerName() + ":"+ request.getServerPort() + path + "/";
String userId = xtag.getParameter(request, "userId");
String msg = ""; String userid = xtag.getParameter(request, "userid");
String lx = xtag.getParameter(request, "lx");
String ip = xtag.getParameter(request, "ip");
String id = xtag.getParameter(request, "id");
String create_time = xtag.getParameter(request, "createtime");
//对当前登陆验证消息进行判断
//-获取数据库当前时间
String time_now = DBManager.getValue("select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual",new String[]{});
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(time_now);
String ss = create_time.substring(0, 4) + "-" + create_time.substring(4, 6) + "-" + create_time.substring(6, 8) + " " + create_time.substring(8, 10) + ":" + create_time.substring(10, 12) + ":" + create_time.substring(12, 14);
Date date2 = sdf.parse(ss);
long minutes=(date1.getTime()-date2.getTime())/(1000);//秒
if( minutes > 60){
msg = "该条信息已过时!";
}else{
Map map = new HashMap();
map = SQLUtils.getSDKMessageMap(id);
if(map == null || (map.size() == 0) || "null".equals(map.get("STATUS")) || "".equals(map.get("STATUS"))){
msg = "该条信息已过时!";
}else if("2".equals(XDataConvert.TryToString(map.get("STATUS")))){
msg = "该条信息已过时!";
}else if("3".equals(XDataConvert.TryToString(map.get("STATUS")))){
msg = "该条信息已取消处理,请操作最新发送的申请!";
}else if("4".equals(XDataConvert.TryToString(map.get("STATUS")))){
msg = "该信息已处理,无法进行操作!";
}
} %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<base href="<%= basePath%>">
<title>面部识别验证中</title>
<meta name="description" content="Static &amp; Dynamic Tables" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" href="./css/ace/css/bootstrap.css" />
<link rel="stylesheet" href="./css/ace/css/font-awesome.css" />
<link rel="stylesheet" href="./css/ace/css/bootstrap-datepicker3.css" />
<link rel="stylesheet" href="./css/ace/css/bootstrap-datetimepicker.css" />
<link rel="stylesheet" href="./css/ace/css/ace-fonts.css" />
<link rel="stylesheet" href="./css/ace/css/ace.css" class="ace-main-stylesheet" id="main-ace-style" />
<link rel="stylesheet" href="./css/ace/css/jquery-ui.custom.css" />
<link rel="stylesheet" href="./css/ace/css/jquery.gritter.css" />
<link rel="stylesheet" href="./css/dialog-skin/simple/ymPrompt.css" />
<!--webuploader CSS-->
<link href="<%=basePath %>css/zui/css/zui.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<%=basePath %>css/zui/lib/datetimepicker/datetimepicker.css">
<link rel="stylesheet" type="text/css" href="<%=basePath %>css/zui/lib/kindeditor/kindeditor.min.css">
<script src="<%=path%>/js/ymPrompt.js"></script>
<!--[if lte IE 9]>
<link rel="stylesheet" href="./css/ace/css/ace-part2.css" class="ace-main-stylesheet" />
<![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="./css/ace/css/ace-ie.css" />
<![endif]-->
<!-- inline styles related to this page -->
<!-- ace settings handler -->
<script src="./css/ace/js/ace-extra.js"></script>
<!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries -->
<!--[if lte IE 8]>
<script src="./css/ace/js/html5shiv.js"></script>
<script src="./css/ace/js/respond.js"></script>
<![endif]-->
<link rel="stylesheet" href="./css/zui/css/zui.min.css" />
<link rel="stylesheet" href="./css/ace/css/chosen.css" />
<!-- jQuery (ZUI中的Javascript组件依赖于jQuery) -->
<script src="<%=basePath %>js/jquery-2.2.0.min.js"></script>
<!-- ZUI Javascript组件 -->
<script src="<%=basePath %>css/ace/js/bootstrap.js"></script>
<script src="<%=basePath %>css/ace/js/chosen.jquery.js"></script>
<script src="<%=basePath %>css/ace/js/ace/ace.js"></script>
<script src="<%=basePath %>css/zui/js/zui.min.js"></script>
<script src="<%=basePath %>css/zui/lib/datetimepicker/datetimepicker.js"></script>
<script src="<%=basePath %>css/zui/lib/kindeditor/kindeditor.min.js"></script>
<style type="text/css">
.chosen-choices {padding: 0px;}
table tr{
height:25px;
}
table tr td{
padding: 4px;
}
</style>
<script type="text/javascript">
window.onload = function page_init() {
if('' == '<%= msg%>' || 'null' == '<%= msg%>'){
window.location.href = '<%= path%>/work/common/camera.jsp?userid=<%= userid%>&lx=<%=lx%>&ip=<%=ip%>&id=<%=id%>';
}else{
//ymPrompt.alert('<%= msg%>');
//$("#outMessage").html('<%= msg%>');
//$("#outMessage").val('<%= msg%>');
var data = '<%= msg%>';
if(null!=data&&""!=data.trim()){
new $.zui.Messager(data, {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement: 'top_left',
close: false,
time: 0 , //0 为不自动隐藏
}).show();
}
}
} //$("#outMessage").html(result_message);
</script>
</head>
<body class="no-skin" style="background-color: #fff;">
<%--
<div align="center" >
<div class="alert alert-warning-inverse" id="outMessage" style="font-size: 18pt;margin-top: 20px"></div>
</div>
--%>
<%--
<div id="outMessage">
</div>
--%>
<!-- basic scripts --> <!--[if !IE]> -->
<script type="text/javascript">
window.jQuery || document.write("<script src='./css/ace/js/jquery.js'>"+"<"+"/script>");
</script> <!-- <![endif]-->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='./css/ace/js/jquery1x.js'>"+"<"+"/script>");
</script>
<![endif]-->
<script type="text/javascript">
if('ontouchstart' in document.documentElement) document.write("<script src='./css/ace/js/jquery.mobile.custom.js'>"+"<"+"/script>");
</script>
<script src="./css/ace/js/bootstrap.js"></script>
<script src="./css/ace/js/chosen.jquery.js"></script>
<!-- CESHI --> <script src="./css/ace/js/date-time/moment.js"></script>
<script src="./css/ace/js/date-time/bootstrap-datepicker.js"></script>
<script src="./css/ace/js/date-time/bootstrap-datetimepicker.js"></script>
<script src="./css/ace/js/ace/elements.scroller.js"></script>
<script src="./css/ace/js/ace/elements.scroller.js"></script>
<script src="./css/ace/js/ace/elements.colorpicker.js"></script>
<script src="./css/ace/js/ace/elements.fileinput.js"></script>
<script src="./css/ace/js/ace/elements.typeahead.js"></script>
<script src="./css/ace/js/ace/elements.wysiwyg.js"></script>
<script src="./css/ace/js/ace/elements.spinner.js"></script>
<script src="./css/ace/js/ace/elements.treeview.js"></script>
<script src="./css/ace/js/ace/elements.wizard.js"></script>
<script src="./css/ace/js/ace/elements.aside.js"></script>
<script src="./css/ace/js/ace/ace.js"></script>
<script src="./css/ace/js/bootbox.js"></script>
<script src="./css/ace/js/ace/ace.ajax-content.js"></script>
<script src="./css/ace/js/ace/ace.touch-drag.js"></script>
<script src="./css/ace/js/ace/ace.sidebar.js"></script>
<script src="./css/ace/js/ace/ace.sidebar-scroll-1.js"></script>
<script src="./css/ace/js/ace/ace.submenu-hover.js"></script>
<script src="./css/ace/js/ace/ace.widget-box.js"></script>
<script src="./css/ace/js/ace/ace.settings.js"></script>
<script src="./css/ace/js/ace/ace.settings-rtl.js"></script>
<script src="./css/ace/js/ace/ace.settings-skin.js"></script>
<script src="./css/ace/js/ace/ace.widget-on-reload.js"></script>
<script src="./css/ace/js/ace/ace.searchbox-autocomplete.js"></script>
<!-- the following scripts are used in demo only for onpage help and you don't need them -->
<link rel="stylesheet" href="./css/ace/css/ace.onpage-help.css" />
<link rel="stylesheet" href="./css/ace/js/themes/sunburst.css" />
<script type="text/javascript"> ace.vars['base'] = '..'; </script>
<script src="./css/ace/js/ace/elements.onpage-help.js"></script>
<script src="./css/ace/js/ace/ace.onpage-help.js"></script>
<script src="./css/ace/js/rainbow.js"></script>
<script src="./css/ace/js/language/generic.js"></script>
<script src="./css/ace/js/language/html.js"></script>
<script src="./css/ace/js/language/css.js"></script>
<script src="./css/ace/js/language/javascript.js"></script>
<script src="./js/js.js"></script>
<script src="<%= path%>/js/layer/layer.js"></script>
<script type="text/javascript">
$(function(){
dyreg('panel1', '12');
})
//当浏览器大小变化时
$(window).resize(function () {
dyreg('panel1', '12');
});
</script>
</body>
</html>

sdk_xxpd

      3.如果OK,进入camera.jsp页面调用摄像头进行拍照。 

 <%@page import="com.cwai.xtag.xTable"%>
<%@page import="com.cwai.logic.dao.PageDD"%>
<%@page import="com.cwai.ado.PageList"%>
<%@page import="com.cwai.logic.task.sql.TaskSQL"%>
<%@page import="com.cwai.logic.bean.User"%>
<%@page import="com.cwai.dao.DBManager"%>
<%@page import="com.cwai.ado.XDataConvert"%>
<%@page import="com.cwai.xtag.xtag"%>
<%@page import="com.cwai.cfg.Configs"%>
<%@page import="org.daisy.daisyframework.mobile.dd.AuthHelper"%>
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String agentId = XDataConvert.TryToString(session.getAttribute("agentId"));
if("".equals(agentId)) {
agentId = Configs.getAgentid();
}
String userid = xtag.getParameter(request, "userid");
String lx = xtag.getParameter(request, "lx");
String ip = xtag.getParameter(request, "ip");
String id = xtag.getParameter(request, "id"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content="yes" name="apple-mobile-web-app-capable"/>
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection"/>
<meta content="yes" name="apple-touch-fullscreen"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"> <script src="<%=basePath%>js/jqueyweui/lib/jquery-2.1.4.js"></script> <title>全流程集成管理平台</title>
<script type="text/javascript" src="http://g.alicdn.com/dingding/open-develop/1.9.0/dingtalk.js"></script>
<script type="text/javascript" src="<%=path%>/www/ddpt/javascripts/logger.js"></script> <link href="<%=basePath %>css/zui/css/zui.min.css" rel="stylesheet">
<link rel="stylesheet" href="<%=basePath %>css/ace/css/bootstrap.css" />
<link rel="stylesheet" href="<%=basePath %>css/ace/css/font-awesome.css" />
<link rel="stylesheet" href="<%=basePath %>css/ace/css/ace-fonts.css" />
<link rel="stylesheet" href="<%=basePath %>css/ace/css/ace.css" class="ace-main-stylesheet" id="main-ace-style" />
<link rel="stylesheet" href="<%=basePath %>css/ace/css/ace.onpage-help.css" />
<link rel="stylesheet" href="<%=basePath %>css/ace/js/themes/sunburst.css" /> <link rel="stylesheet" href="<%=basePath %>css/ace/css/jquery-ui.custom.css" />
<link rel="stylesheet" href="<%=basePath %>css/ace/css/jquery.gritter.css" />
<link rel="stylesheet" href="<%=basePath %>css/dialog-skin/simple/ymPrompt.css" /> <!--webuploader CSS-->
<link rel="stylesheet" type="text/css" href="<%=basePath %>css/zui/lib/datetimepicker/datetimepicker.css">
<link rel="stylesheet" type="text/css" href="<%=basePath %>css/zui/lib/kindeditor/kindeditor.min.css">
<script type="text/javascript">
window.jQuery || document.write("<script src='<%= path%>/css/ace/js/jquery.js'>"+"<"+"/script>");
</script> <!-- ZUI Javascript组件 --> <link rel="stylesheet" href="<%= path%>/css/dialog-skin/simple/ymPrompt.css" />
<script src="<%= path%>/js/ymPrompt.js"></script> <!-- jQuery (ZUI中的Javascript组件依赖于jQuery) -->
<script src="<%=basePath %>js/jquery-2.2.0.min.js"></script>
<!-- ZUI Javascript组件 -->
<script src="<%=basePath %>css/zui/js/zui.min.js"></script>
<script src="<%=basePath %>css/ace/js/bootstrap.js"></script>
<script src="<%=basePath %>css/ace/js/chosen.jquery.js"></script>
<script src="<%=basePath %>css/ace/js/ace/ace.js"></script>
<script src="<%=basePath %>css/zui/lib/datetimepicker/datetimepicker.js"></script>
<script src="<%=basePath %>css/zui/lib/kindeditor/kindeditor.min.js"></script>
<script src="<%= path%>/js/layer/layer.js"></script>
<link rel="stylesheet" href="<%= path%>/js/select2/css/select2.css" />
<script src="<%= path%>/js/select2/js/select2.js"></script> <script type="text/javascript">
//在此拿到权限验证配置所需要的信息 钉钉平台拍照
var _config = <%= AuthHelper.getConfig(request, Configs.getCorpID(), agentId) %>;
dd.config({
agentId : _config.agentid,
corpId : _config.corpId,
timeStamp : _config.timeStamp,
nonceStr : _config.nonceStr,
signature : _config.signature,
jsApiList : [ 'runtime.info', 'biz.contact.choose',
'device.notification.confirm', 'device.notification.alert',
'device.notification.prompt', 'biz.ding.post',
'biz.util.openLink', 'device.geolocation.get', 'biz.util.scan', 'biz.map.locate', 'biz.util.uploadImageFromCamera', 'biz.navigation.close']
}); function close_win() {
dd.biz.navigation.close({
onSuccess : function(result) {
/*result结构
{}
*/
},
onFail : function(err) {}
});
} dd.ready(function(){
dd.biz.util.uploadImageFromCamera({
compression: true,//(是否压缩,默认为true)
quality: 50, // 图片压缩质量,
resize: 50, // 图片缩放率
stickers: { // 水印信息
},
onSuccess : function(result) {
var str = result +"~<%= userid%>~<%=id%>" ;
//var result_message = ajaxGetData("SDKRESULT",str);//getdata.jsp
$.ajax({
url:"<%= path%>/ajax/getitems.jsp", //请求的url地址
dataType: "text", //返回格式为json
async: false,
data: {"DMZL" : "SDKRESULT", "queryValue" : str },
type:"post", //请求方式
success:function(data){
var re = new Array();
re = data.split("~"); if(null != re[1] && "" != re[1].trim()){ if("OK" == re[0].trim()){
new $.zui.Messager(re[1], {
type: 'success' ,// 定义颜色主题
icon: 'smile',
placement:'top-left',
close: false,
time: 0 //0 为不自动隐藏
}).show();
//alert("成功音乐播放");
//音乐播放
var file1 = [];
file1['mp3'] = '<%=path%>/sound/success.mp3';//文件路径
audioplayer('audioplane', file1, false);
}else{
new $.zui.Messager(re[1], {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement:'top-left',
close: false,
time: 0 //0 为不自动隐藏
}).show();
//alert("失败音乐播放");
//音乐播放
var file2 = [];
file2['mp3'] = '<%=path%>/sound/fail.mp3';//文件路径
audioplayer('audioplane', file2, false);
} setTimeout("close_win()", 2000);
}
}
});
},
onFail : function(err) {
//$("#outMessage").html(err);
if(null != err && "" != err.trim()){
new $.zui.Messager(err, {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement:'top-left',
close: false,
time: 0 //0 为不自动隐藏
}).show();
}
}
});
}); dd.error(function(err) {
alert('dd error: ' + JSON.stringify(err));
}); /*
用法示例:
var file = [];
file['mp3'] = '1.mp3';
file['ogg'] = '1.ogg';
// 播放
audioplayer('audioplane', file, true);
// 停止
audioplayer('audioplane');
*/
/** 音乐播放器 * @param obj 播放器id * @param file 音频文件 mp3: ogg: * @param loop 是否循环 */
function audioplayer(id, file, loop){
var audioplayer = document.getElementById(id);
if(audioplayer!=null)
{
document.body.removeChild(audioplayer);
}
if(typeof(file)!='undefined')
{
if(navigator.userAgent.indexOf("MSIE")>0)
{
// IE
var player = document.createElement('bgsound');
player.id = id;
player.src = file['mp3'];
player.setAttribute('autostart', 'true');
if(loop){ player.setAttribute('loop', 'infinite');
}
document.body.appendChild(player);
}else{
// Other FF Chome Safari Opera
var player = document.createElement('audio');
player.id = id;
player.setAttribute('autoplay', 'autoplay');
if (loop) {
player.setAttribute('loop', 'loop');
}
document.body.appendChild(player);
var mp3 = document.createElement('source');
mp3.src = file['mp3'];
mp3.type = 'audio/mpeg';
player.appendChild(mp3);
var ogg = document.createElement('source');
ogg.src = file['ogg'];
ogg.type = 'audio/ogg';
player.appendChild(ogg);
}
}
} </script>
<style type="text/css"> </style>
</head>
<body>
<div id="outMessage"></div>
</body>
</html>

camera

      4.调用Ajax对照片进行比对,返回结果,同时内网实时检测结果,并做出相应处理

    步骤2(模式2):

      1..java文件实时读取、发送消息到钉钉,

      2.打开钉钉消息,进入主页面,显示【签字】按钮(同时用到遮罩层的实现)   

 1.
<%@page import="com.cwai.cfg.Configs"%>
<%@page import="org.daisy.daisyframework.mobile.dd.AuthHelper"%> 2.
//获取当前用户的签字模式
Map map_ms = DBManager.singleData("SELECT USERID,QZMS FROM BM_USER_INFO WHERE USERID = '"+user.getUserId()+"'", new String[]{});
String qzms = XDataConvert.TryToString(map_ms.get("QZMS")); 3.
<!-- 遮罩层css代码(两种样式,看喜好选择) -->
<style type="text/css">
.mask1 {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
bottom: 0px;
display: none;
background: rgba(0, 0, 0, 0.4);
} .mask2 {
position: fixed;
left: 0px;
top: 0px;
right: 0px;
bottom: 0px;
display: none;
background: rgba(0, 0, 0, 0.4);
}
</style>
4.
//单击事件绑定
onclick="signature('20161226024039000043','<%=user.getUserId() %>','QM','')" 5.
<!-- 遮罩层 -->
<div class="mask1"></div>
<div class="mask2"></div> 6.
//调用的JS
<script src="<%= path%>/js/qm.js"></script>
<!-- 用于调用摄像头 -->
<script type="text/javascript" src="http://g.alicdn.com/dingding/open-develop/1.9.0/dingtalk.js"></script>
<script type="text/javascript" src="<%=path%>/www/ddpt/javascripts/logger.js"></script> 7.
window.onload=function(){
//初始化遮罩层隐藏
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
} //获取使用的变量
var ny = '<%= new SimpleDateFormat("yyyy-MM-dd").format(new Date())%>';
var qzms = "<%=qzms%>";
var path = "<%=path%>";
//签名
function signature(id,userid,lx,qzrq){
//打开遮罩层
document.querySelector(".mask2").style.display = "block";
//document.querySelector(".mask2").style.display = "block";
qmxz(qzms,path,id,userid,lx,qzrq);
} //用于调用摄像头
var _config = <%= AuthHelper.getConfig(request, Configs.getCorpID(), Configs.getAgentid()) %>;
dd.config({
agentId : _config.agentid,
corpId : _config.corpId,
timeStamp : _config.timeStamp,
nonceStr : _config.nonceStr,
signature : _config.signature,
jsApiList : [ 'runtime.info', 'biz.contact.choose',
'device.notification.confirm', 'device.notification.alert',
'device.notification.prompt', 'biz.ding.post',
'biz.util.openLink', 'device.geolocation.get', 'biz.util.scan', 'biz.map.locate', 'biz.util.uploadImageFromCamera', 'biz.navigation.close']
});

主页面需添加代码

      3.单击【签字】按钮,弹出选择签字模式对话框(本项目设4类   1 混合验证(默认密码) 2混合验证(默认人脸识别) 3仅密码验证  4仅人脸识别验证 )

        如果是3、4情况则直接进入,不需要弹出选择对话框

//20180502人脸识别新增遮罩层

var v_result = '';
dd.error(function(err) {
alert('dd error: ' + JSON.stringify(err));
}); /**
* 弹出消息进行签字模式的选择
* @param qzms 签字模式
* @param path 项目地址
* @param id 获取图片的ID
* @param userid 用户ID
* @param lx 签名类型(会签:HQ 签名:QM)
* @param qzrq 签字日期
* @param hqshow 会签签名按钮是否显示 0(false):否 1(true)是
*/
function qmxz(qzms,path, id,userid,lx,qzrq,hqshow){
var title = "签名";
var url = path + "/images/login/logininputbg.gif";
var img = "<img src='" + url + "' />";
var content = "";
if("1" == qzms || "3" == qzms){
if("1" == qzms){
//content = "当前签字模式为<br>【密码验证】和【面部识别】验证<br>点击【关闭】按钮将取消验证";
layer.msg("", {
time: 10000, //20s后自动关闭
btn: ['密码验证', '面部识别', '关闭']
,yes:function (index){
layer.close(index);
dzqm(path,id,userid,lx,qzrq,hqshow);
},btn2:function (index){
layer.close(index);
sdk(path,id,userid,lx,qzrq,hqshow);
},btn3:function (index){
layer.close(index);
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}
});
}else{
dzqm(path,id,userid,lx,qzrq,hqshow);
}
}else if("2" == qzms || "4" == qzms){
if("2" == qzms){
//content = "当前签字模式为【面部识别】验证<br>点击【切换】按钮切换至【密码验证】<br>点击【确认】按钮进行【面部识别】验证";
layer.msg("", {
time: 10000, //20s后自动关闭
btn: ['密码验证', '面部识别', '关闭']
,yes:function (index){
layer.close(index);
dzqm(path,id,userid,lx,qzrq,hqshow);
},btn2:function (index){
layer.close(index);
sdk(path,id,userid,lx,qzrq,hqshow);
},btn3:function (index){
layer.close(index);
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}
});
}else{
sdk(path,id,userid,lx,qzrq,hqshow);
}
}
}
/**
* 电子签名方式进行签名
* @param id
* @param userid
*/
function dzqm(path, id, userid,lx,qzrq,hqshow){
layer.prompt({
title: '输入签字密码,并确认',
formType: 1,
btn2:function(index){
layer.close(index);
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}
},
function(pass, index){
layer.close(index);
$.ajax({
type: "POST",
url: path + "/ajax/formdata.jsp",
data: {type: 'SIGNATURE',userid: userid,pass: pass},
dataType: "json",
success:function(data){
//console.log(data);
if(data.code == 2){
if("QM" == lx.trim()){
var src = path + "/work/common/view_image2.jsp?tpid=" + data.qzxxid;
$("#"+id+"_img").attr("src",src);
$("#"+id).val(data.qzxxid);
$("#"+id+"_btn").hide();
$("#"+id+"_img").show();
if("" != qzrq && null != qzrq ){
$("#"+qzrq).val(ny);
}
}else if("HQ" == lx.trim()){
app.huiqian.push({
userid: userid,
imgid: data.qzxxid
});
if("0" == hqshow){
app.hqshow = false;
}else {
$("#"+id+"_btn").hide();
}
}
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}else{
layer.msg(data.msg, {icon: 2, time: 3000});
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}
}
})
}
);
} /**
* 人脸识别方式进行签字
* @param path
* @param id
* @param userid
* @param lx
* @param qzrq
* @param hqshow
*/
function sdk(path, id, userid,lx,qzrq,hqshow){
/*
var index = layer.open({
type: 2,
content: path + '/work/common/camera_out.jsp?userid='+userid+'&id='+id+'&lx='+lx+'&qzrq='+qzrq+'&hqshow='+hqshow,
area: ['320px', '195px'],
maxmin: true
});
*/
var v_path = path + '/work/common/camera_out.jsp?userid='+userid+'&id='+id+'&lx='+lx+'&qzrq='+qzrq+'&hqshow='+hqshow;
dd.ready(function(){ dd.biz.util.uploadImageFromCamera({
compression: true,//(是否压缩,默认为true)
quality: 50, // 图片压缩质量,
resize: 50, // 图片缩放率
stickers: { // 水印信息
},
onSuccess : function(result) {
if(document.getElementById("camera_frame") == null) {
$("body").append("<iframe name='camera_frame' id='camera_frame' src='"+ v_path +"' style='display:none'/>");
} else {
$("#camera_frame").attr("src", v_path);//注意src赋值的方式
}
v_result = result;
},
onFail : function(err) { }
}); document.addEventListener('resume', function() {
document.querySelector(".mask1").style.display = "none";
document.querySelector(".mask2").style.display = "none";
}); document.addEventListener('pause', function() {
//alert("页面不可见");// 在这里处理你的业务逻辑
});
});
/*
if(document.getElementById("camera_frame") == null) {
$("body").append("<iframe id='camera_frame' src='"+ v_path +"' style='display:none'/>");
} else {
$("#camera_frame").attr("src") = v_path;
}
*/
//window.open(); /*
//path + '/work/common/camera_out.jsp?userid='+userid+'&id='+id+'&lx='+lx+'&qzrq='+qzrq+'&hqshow='+hqshow
//var dataurl = "#springUrl('/work/common/camera_out.jsp')?userid="+selectManagerDept+"&id="+id+"&lx="+lx+"&qzrq="+qzrq+"&hqshow="+hqshow;
var dataurl = 'http://layim.layui.com';
var index = layer.open({
type: 2,
content: dataurl,
area: ['320px', '195px'],
maxmin: true;
}); ymPrompt.win({
message: path + '/work/common/camera_out.jsp?userid='+userid+'&id='+id+'&lx='+lx+"&qzrq="+qzrq+"&hqshow="+hqshow,
width:200, height:300,
title:'人脸识别签名',
handler: function(flag) {
},
minBtn:true,
iframe:true
});
*/
}

qm.js

      4.选择模式,进入对应签字情况

        面部识别(主要展示):

        进入camera_out.jsp页面进行图片的比对(同时用到MP3

的播放)        

 <%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.cwai.xtag.xTable"%>
<%@page import="com.cwai.logic.dao.PageDD"%>
<%@page import="com.cwai.ado.PageList"%>
<%@page import="com.cwai.logic.task.sql.TaskSQL"%>
<%@page import="com.cwai.logic.bean.User"%>
<%@page import="com.cwai.dao.DBManager"%>
<%@page import="com.cwai.ado.XDataConvert"%>
<%@page import="com.cwai.xtag.xtag"%>
<%@page import="com.cwai.cfg.Configs"%>
<%@page import="org.daisy.daisyframework.mobile.dd.AuthHelper"%>
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String agentId = XDataConvert.TryToString(session.getAttribute("agentId"));
if("".equals(agentId)) {
agentId = Configs.getAgentid();
}
String userid = xtag.getParameter(request, "userid");
String id = xtag.getParameter(request, "id");
String lx = xtag.getParameter(request, "lx");
String qzrq = xtag.getParameter(request, "qzrq");
String hqshow = xtag.getParameter(request, "hqshow"); System.out.println("------------------------开始拍照---------------------------------");
System.out.println("------------------------开始拍照---------------------------------");
System.out.println("------------------------开始拍照---------------------------------"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content="yes" name="apple-mobile-web-app-capable"/>
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection"/>
<meta content="yes" name="apple-touch-fullscreen"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"> <script src="<%=basePath%>js/jqueyweui/lib/jquery-2.1.4.js"></script> <title>全流程集成管理平台</title>
<script type="text/javascript" src="http://g.alicdn.com/dingding/open-develop/1.9.0/dingtalk.js"></script>
<script type="text/javascript" src="<%=path%>/www/ddpt/javascripts/logger.js"></script> <script type="text/javascript">
window.jQuery || document.write("<script src='<%= path%>/css/ace/js/jquery.js'>"+"<"+"/script>");
</script>
<!-- ZUI Javascript组件 --> <link rel="stylesheet" href="<%= path%>/css/dialog-skin/simple/ymPrompt.css" />
<script src="<%= path%>/js/ymPrompt.js"></script> <!-- jQuery (ZUI中的Javascript组件依赖于jQuery) -->
<script src="<%=basePath %>js/jquery-2.2.0.min.js"></script>
<!-- ZUI Javascript组件 -->
<link href="<%=basePath %>css/zui/css/zui.min.css" rel="stylesheet">
<script src="<%=basePath %>css/zui/js/zui.min.js"></script>
<script src="<%= path%>/js/layer/layer.js"></script> <script type="text/javascript">
//在此拿到权限验证配置所需要的信息 钉钉平台拍照 window.onload = function page_init() {
//alert("进入camora");
f_success(window.parent.v_result);
} var id = '<%=id%>';
var userid = '<%=userid%>';
//用于签名时间(FORM_20170117050524000077.jsp)
var qzrq = '<%=qzrq%>';
var ny = '<%= new SimpleDateFormat("yyyy-MM-dd").format(new Date())%>';
var hqshow = '<%=hqshow%>'; function f_success(result) {
var str = result +"~<%= userid%>" ;
//var result_message = ajaxGetData("SDKRESULT",str);//getdata.jsp
//alert("str______________"+str);
$.ajax({
url:"<%= path%>/ajax/getitems.jsp", //请求的url地址
dataType: "text", //返回格式为json
async: false,
data: {"DMZL" : "SDKRESULT_OUT", "queryValue" : str },
type:"post", //请求方式
success:function(data){
var re = new Array();
re = data.split("~");
if(null != re[1] && "" != re[1].trim()){
if("OK" == re[0].trim()){
//alert("re[0].trim():"+re[0].trim());
//获取qzxxid
$.ajax({
url : '<%= path%>/ajax/getitems.jsp',
type : 'POST',
dataType : 'text',
data : {"DMZL":"GETQZXXID", "queryValue": '<%= userid%>' },
success : function(qzxx){
///alert("qzxx:"+qzxx);
//进行图片签字,显示图片
if("0" == qzxx.trim()){
//失败音乐播放
var file2 = [];
file2['mp3'] = '<%=path%>/sound/fail.mp3';//文件路径
audioplayer('audioplane', file2, false);
//提示信息
new window.parent.$.zui.Messager("没有被应用的签字,请先设置签字!", {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement:'center',
close: false, //不需要关闭按钮
time: 0 , //0 为不自动隐藏
actions: [{
name: 'undo',
icon: 'undo',
text: '关闭',
action: function() { // 点击该操作按钮的回调函数
//隐藏遮罩层
window.parent.document.querySelector(".mask1").style.display = "none";
window.parent.document.querySelector(".mask2").style.display = "none";
//return false; // 通过返回 false 来阻止消息被点击时隐藏
}
}]
}).show();
}else{
//成功音乐播放
var file1 = [];
file1['mp3'] = '<%=path%>/sound/success.mp3';//文件路径
audioplayer('audioplane', file1, false);
//提示音乐播放完毕自动关闭
//alert("<%=lx%>");
if("QM" == "<%=lx%>"){
var src = "<%=path%>/work/common/view_image2.jsp?tpid=" + qzxx.trim();
window.parent.$("#"+id+"_img").attr("src",src);
window.parent.$("#"+id).val(qzxx.trim());
window.parent.$("#"+id+"_btn").hide();
window.parent.$("#"+id+"_img").show();
if("" != qzrq && null != qzrq ){
window.parent.$("#"+qzrq).val(ny);
}
//隐藏遮罩层
window.parent.document.querySelector(".mask1").style.display = "none";
window.parent.document.querySelector(".mask2").style.display = "none";
}else if("HQ" == "<%=lx%>"){
window.parent.app.huiqian.push({
userid: userid,
imgid: qzxx.trim()
});
if("0" == hqshow){
window.parent.app.hqshow = false;
}else {
window.parent.$("#"+id+"_btn").hide();
}
//隐藏遮罩层
window.parent.document.querySelector(".mask1").style.display = "none";
window.parent.document.querySelector(".mask2").style.display = "none";
} }
}
});
}else{
//失败音乐播放
var file2 = [];
file2['mp3'] = '<%=path%>/sound/fail.mp3';//文件路径
audioplayer('audioplane', file2, false);
//提示信息
new window.parent.$.zui.Messager(re[1].trim(), {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement:'center',
close: false, //不需要关闭按钮
time: 0 , //0 为不自动隐藏
actions: [{
name: 'undo',
icon: 'undo',
text: '关闭',
action: function() { // 点击该操作按钮的回调函数
//隐藏遮罩层
window.parent.document.querySelector(".mask1").style.display = "none";
window.parent.document.querySelector(".mask2").style.display = "none";
//return false; // 通过返回 false 来阻止消息被点击时隐藏
}
}]
}).show(); }
}
}
});
} function f_error(err) {
new $.zui.Messager(re[1], {
type: 'warning' ,// 定义颜色主题
icon: 'warning-sign',
placement:'top-left',
close: false,
time: 0 //0 为不自动隐藏
}).show();
} /*
用法示例:
var file = [];
file['mp3'] = '1.mp3';
file['ogg'] = '1.ogg';
// 播放
audioplayer('audioplane', file, true);
// 停止
audioplayer('audioplane');
*/
/** 音乐播放器 * @param obj 播放器id * @param file 音频文件 mp3: ogg: * @param loop 是否循环 */
function audioplayer(id, file, loop){
var audioplayer = document.getElementById(id);
if(audioplayer!=null)
{
document.body.removeChild(audioplayer);
}
if(typeof(file)!='undefined')
{
if(navigator.userAgent.indexOf("MSIE")>0)
{
// IE
var player = document.createElement('bgsound');
player.id = id;
player.src = file['mp3'];
player.setAttribute('autostart', 'true');
if(loop){ player.setAttribute('loop', 'infinite');
}
document.body.appendChild(player);
}else{
// Other FF Chome Safari Opera
var player = document.createElement('audio');
player.id = id;
player.setAttribute('autoplay', 'autoplay');
if (loop) {
player.setAttribute('loop', 'loop');
}
document.body.appendChild(player);
var mp3 = document.createElement('source');
mp3.src = file['mp3'];
mp3.type = 'audio/mpeg';
player.appendChild(mp3);
var ogg = document.createElement('source');
ogg.src = file['ogg'];
ogg.type = 'audio/ogg';
player.appendChild(ogg);
}
}
} </script>
<style type="text/css"> </style>
</head>
<body>
<%
System.out.println("------------------------拍照结束---------------------------------");
System.out.println("------------------------拍照结束---------------------------------");
System.out.println("------------------------拍照结束---------------------------------");
%>
<div id="outMessage">
</div>
</body>
</html>

camera_out

 <%@page import="com.cwai.util.SDKMatch"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%@page import="com.cwai.xtag.xtag"%>
<%@page import="com.cwai.logic.task.sql.TaskSQL"%>
<%@page import="org.daisy.daisyframework.util.DataConvertor"%>
<%@page import="com.cwai.pass.Md5"%>
<%@page import="com.cwai.dao.DBManager"%>
<%@page import="com.cwai.logic.bean.User"%>
<%@ page language="java" import="java.util.*,com.cwai.bean.*,com.cwai.xbean.*,com.cwai.ado.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath(); if(null==session||session.getAttribute("LoginUser")==null){out.println("<script language='javascript'> function reLongin(){top.window.PAGE_FLAG = false;top.location='"+path+"/fail.jsp?ID=001'"+"}</script> ");out.println("<script language='javascript'> reLongin();</script> ");return;}
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
//代码种类
String dmzl=request.getParameter("DMZL")==null?"":request.getParameter("DMZL").toUpperCase();
//查询代码
String v=request.getParameter("queryValue")==null?"":request.getParameter("queryValue");
BaseDAO dao = null;
try{
dao = new BaseDAO();
if("GETQZXXID".equals(dmzl)){//根据userid获取签字信息ID
System.out.println("获取当前图片的比对结果_GETQZXXID:__________开始___________________");
System.out.println("获取当前图片的比对结果_GETQZXXID:__________开始___________________");
System.out.println("获取当前图片的比对结果_GETQZXXID:__________开始___________________");
String qzxxid = dao.getValue("SELECT QZXX_ID FROM BM_USER_DZQZ T WHERE USERID = '"+v.trim()+"' AND SFYY = 1 AND DQYX = 1", new Object[]{});
System.out.println("获取当前图片的比对结果_GETQZXXID:__________开始___________________"+qzxxid);
if("".equals(qzxxid) || null == qzxxid){
out.println("0");
}else{
out.println(qzxxid.trim());
}
}else if("SDKRESULT_OUT".equals(dmzl)){//根据用户ID获取线上拍照头像比对结果
System.out.println("获取当前图片的比对结果_out:__________开始___________________");
String[] re = v.split("~");
//获取当前图片的比对结果
String flag = SDKMatch.faceCompare(re[0], re[1]);
System.out.println("获取当前图片的比对结果_out——flag:_____________________________"+flag);
String rtn_data = "头像比对未通过!";
if("OK".equals(flag)){
rtn_data = "面部识别通过!";
}else if("LIVE_NO".equals(flag)){
rtn_data = "活体验证失败!";
}else if("NO".equals(flag)){
rtn_data = "面部识别未通过。未通过原因:非本人面部!";
}else if("MAP_NO".equals(flag)){
rtn_data = "未设置主头像,请密码登陆设置后,再次操作!";
}else if("FACE_NO".equals(flag)){
rtn_data = "面部识别未通过。未通过原因:拍摄时未对准面部!";
}
System.out.println("获取当前图片的比对结果_out:_____________________结束____________________");
out.print(flag+"~"+rtn_data);
} else if("SDKRESULT".equals(dmzl)){//根据用户ID获取线上拍照头像比对结果
System.out.println("获取当前图片的比对结果:_____________开始________________");
String[] re = v.split("~");
//获取当前图片的比对结果
String flag = SDKMatch.faceCompare(re[0], re[1]);
System.out.println("获取当前图片的比对结果:_____________________________"+flag);
String rtn_data = "头像比对未通过!";
boolean ff = false;
if("OK".equals(flag)){
ff = DBManager.execute(" UPDATE DD_SDKMESSAGE SET FINISH_TIME = SYSDATE ,STATUS = '4' WHERE ID = '" + re[2] + "' ", new String[]{});
rtn_data = "面部识别通过!";
}else if("LIVE_NO".equals(flag)){
ff = DBManager.execute(" UPDATE DD_SDKMESSAGE SET FINISH_TIME = SYSDATE, STATUS = '5' WHERE ID = '" + re[2] + "' ", new String[]{});
rtn_data = "活体验证失败!";
}else if("NO".equals(flag)){
ff = DBManager.execute(" UPDATE DD_SDKMESSAGE SET FINISH_TIME = SYSDATE, STATUS = '1' WHERE ID = '" + re[2] + "' ", new String[]{});
rtn_data = "面部识别未通过。未通过原因:非本人面部!";
}else if("MAP_NO".equals(flag)){
rtn_data = "未设置主头像,请密码登陆设置后,再次操作!";
}else if("FACE_NO".equals(flag)){
rtn_data = "面部识别未通过。未通过原因:拍摄时未对准面部!";
}
System.out.println("ff:_________________________________________"+ff);
out.print(flag+"~"+rtn_data);
}

getitems

注:1.getitems.jsp中内容仅作参考,根据项目要求来定

2.本项目使用的是百度AI版本2

      

      

上一篇:bate版说明书


下一篇:【计算机视觉】基于OpenCV的人脸识别