javaweb项目中嵌入百度人脸识别实现登录/打卡功能包含前端代码

public class FaceMatch {

//    /**
//    * 重要提示代码中所需工具类
//    * FileUtil,Base64Util,HttpUtil,GsonUtils请从
//    * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
//    * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
//    * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
//    * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
//    * 下载
//    */
	[
	    {
	        "image": "sfasq35sadvsvqwr5q...",
	        "image_type": "BASE64",
	        "face_type": "LIVE",
	        "quality_control": "LOW",
	        "liveness_control": "HIGH"
	    },
	    {
	        "image": "sfasq35sadvsvqwr5q...",
	        "image_type": "BASE64",
	        "face_type": "IDCARD",
	        "quality_control": "LOW",
	        "liveness_control": "HIGH"
	    }
	]
//    public static String faceMatch(String param,String accessToken) {
//        // 请求url
//        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
//        try {
            String param = GsonUtils.toJson(map);
            System.out.println("param="+param);
//            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
//            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
	

	public static final String accessToken = "需要自己在百度AI平台申请对应类型的";
	public static final Double  SCORE= 80.00;
	public static String checkErrorMessage(String code) {
		switch(code) {
		case "0":
			return "成功";
			
		case "223113":
			return "人脸被遮挡";
			
		case "223114":
			return "人脸模糊";
			
		case "223115":
			return "人脸光照不好";
			
		case "223116":
			return "人脸不完整";
			
		case "223120":
			return "活体检测未通过";
			
		case "223121":
			return "请勿遮挡左眼";
			
		case "223122":
			return "请勿遮挡右眼";
			
		case "223123":
			return "请勿遮挡左脸";
			
		case "223124":
			return "请勿遮挡右脸";
			
		case "223125":
			return "请勿遮挡下巴";
			
		case "223126":
			return "请勿遮挡鼻子";
			
		case "223127":
			return "请勿遮挡嘴巴";
			
			default:
				return "其他错误类型,请向管理员反馈";
			
		}
	}
	public static String match(String image1,String image2) {

		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
		try {

//			byte[] bytes1 = FileUtil.readFileByBytes("D:\\images\\22.jpg");
//			byte[] bytes2 = FileUtil.readFileByBytes("D:\\images\\33.jpg");
//			byte[] bytes2 = Base64Util.encode(FileUtil.readFileByBytes("D:\\images\\33.jpg"));
//			String image1 = Base64Util.encode(bytes1);
//			String image2 = Base64Util.encode(bytes2);

			List<Map<String, Object>> images = new ArrayList<Map<String, Object>>();

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("image", image1);
			map1.put("image_type", "BASE64");
			map1.put("face_type", "LIVE");
			map1.put("quality_control", "LOW");
			map1.put("liveness_control", "NORMAL");

			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("image", image2);
			map2.put("image_type", "BASE64");
			map2.put("face_type", "LIVE");
			map2.put("quality_control", "LOW");
			map2.put("liveness_control", "NORMAL");

			images.add(map1);
			images.add(map2);

			String param = GsonUtils.toJson(images);

			String result = HttpUtil.post(url, accessToken, "application/json", param);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

//	public static void main(String[] args) {
//		FaceMatch.match();
//	}
}
/**
	 * 课程人脸打卡/登录
	 * 根据type类型是为打卡或则为登录,这边type 1为打卡,2为登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/courseFacePunchOrLogin")
	@ResponseBody
	public Map<String, Object> facePunch(@RequestParam("account") String account,@RequestParam(value = "file", required = false) MultipartFile file
			,@RequestParam("type") Integer type, HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		try {
			if(file.isEmpty()) {
				return setJson(false, "参数错误-照片。", null);
			}
			//修减字符串
			String img=Base64Util.encode(file.getBytes());
			//获取线上图片路径
			String myImg="http://xxxx";
			//请求接口校验人脸识别这个方法是使用本地图片来做比对
			String result=FaceMatch.match(img,
			Base64Util.encode(FileUtil.readFileByBytes("D:/1.png")));
			//线上使用这个方法
			//String result=FaceMatch.match(img, Base64Util.encode(FileUtil.readFileByBytes(myImg)));
			//获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
			String ext = FileUploadUtils.getSuffix(file.getOriginalFilename());
			//获取文件路径
			String filePath="/自定义路径/"+ DateUtils.toString(new Date(), "yyyyMMdd")+"/"+System.currentTimeMillis()+".png";
			//路径校验
			File files = new File(rootpath+"/"+filePath);
			//结束
			//如果目录不存在,则创建
			if(!files.getParentFile().exists()){
				files.getParentFile().mkdirs();
			}
			//保存文件
			file.transferTo(files);
			Gson gson = new Gson();
			//返回的json转换成map
	        Map<String, Object> results = new HashMap<String, Object>();
	        results = gson.fromJson(result, results.getClass());
	        //转换返回结果
	        Map<String, Object> faceSignResult = new HashMap<String, Object>();
	        faceSignResult = gson.fromJson(results.get("result")+"", faceSignResult.getClass());
	        //此处拼装校验参数
	        //--------------
	        //请求成功
	        if(results.get("error_msg").equals("SUCCESS")) {
	        	//推荐校验阀值80分
	        	if(Double.parseDouble(faceSignResult.get("score")+"")>FaceMatch.SCORE) {	
	    	        insertFaceSign.put("statusSgin", 1);    	   
	    	        //判断类型按自定义要求执行登录或则打卡
					//返回结果
	        	}else {
	        		//人脸识别分数低于80判定不为本人
	        		//返回结果
	        	}
	        }else {
    	        //错误原因
    	        //获取error_code会带.0所以需要替换之后并查询错误信息
    	        StringerrorInfo=FaceMatch.checkErrorMessage(results.get("error_code")+"".replaceAll(".0", ""));
				//自定义查
	        	
	        }
	
			switch(type) {
			case 1:
				//要做的打卡操作
				break;
			case 2:
			//要做的登录操作
				break;
				default:
					return setJson(false, "类型错误。", null);
			}
				} catch (Exception e) {
			logger.error("CourseController.courseFacePunch()---error", e);
			this.setAjaxException(setJson(false, e+"", null));
		}
		return null;
	}

你可能感兴趣的:(G工作中的问题)