package com.example.dahua.control; import com.example.dahua.MyTask; import com.example.dahua.async.ImageUtils; import com.example.dahua.async.SendUserInfoTask; import com.example.dahua.lib.CompressPic; import com.example.dahua.service.UserService; import com.example.dahua.utils.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import javax.imageio.stream.FileImageInputStream; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; /** * 用户相关接口 */ @RestController("/user/") @Api(tags = "下发用户信息") @RequestMapping(value = "/user/*",produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class UserControl { @Autowired UserService userService; @Autowired SendUserInfoTask sendUserInfoTask; @Autowired MyTask myTasks; @RequestMapping(value = "uploadImgAndUserInfo", method = RequestMethod.GET) @ApiOperation(value = "上传用户信息") public boolean uploadImgAndUserInfo(@RequestParam("file") String file, @RequestParam("schoolId") String schoolId, @RequestParam("studentCode") String studentCode, @RequestParam("clint_type") String clint_type) { // return userService.uploadImgAndUserInfo(file, schoolId, studentCode, clint_type); return HttpUtils.uploadImgs(new File(file),schoolId,studentCode,clint_type,file.contains("Teacher")?1:2); } @RequestMapping(value = "imgsSend", method = RequestMethod.GET) @ApiOperation(value = "照片下放") public boolean imgsSend(@RequestParam("schoolId") String schoolId, @RequestParam("type") int type) { userService.sendUserInfos(schoolId, "22", type); return true; } @RequestMapping(value = "sendSingle", method = RequestMethod.GET) @ApiOperation(value = "单张卡下发") public String sendSIngle(@RequestParam("SchoolId") String SchoolId, @RequestParam("Card") String Card) { RestTemplate restTemplate = new RestTemplate(); String url = "http://campus.myjxt.com/api/OneCard/SendSingle?SchoolId=" + SchoolId + "&Card=" + Card.toUpperCase().trim(); String result = restTemplate.getForObject(url, String.class); System.out.println("result:" + result); try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.optBoolean("data")) { return "下发成功"; } } catch (JSONException e) { e.printStackTrace(); } return "下发失败"; } @RequestMapping(value = "sendWG", method = RequestMethod.GET) @ApiImplicitParams({@ApiImplicitParam(name = "SchoolId", value = "学校id"), @ApiImplicitParam(name = "StudentType", value = "学生类型,1:通校生,2:住校,3:通晚,4:其他"), @ApiImplicitParam(name = "Sex", value = "性别:1男,2女")}) @ApiOperation(value = "下发附属卡") public String sendWG(@RequestParam("SchoolId") String SchoolId, @RequestParam("StudentType") String StudentType, @RequestParam("Sex") String Sex) { RestTemplate restTemplate = new RestTemplate(); String url = "http://campus.myjxt.com/api/OneCard/SendWG?SchoolId=" + SchoolId + "&StudentType=" + StudentType + "&Sex=" + Sex; String result = restTemplate.getForObject(url, String.class); System.out.println("sendWG:" + result); try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.optBoolean("data")) { return "下发成功"; } } catch (JSONException e) { e.printStackTrace(); } return "下发失败"; } @RequestMapping(value = "checkFace", method = RequestMethod.GET) @ApiOperation("在线活体检测") public boolean checkFace(@RequestParam("url") String httpurl) { // 请求url String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify"; try { List list = new ArrayList(); Map map = new HashMap<>(); String image_type = ""; String imgFilePath = httpurl; File target = new File("./huoti/"); if (!target.exists()) target.mkdirs(); File target1 = new File(target.getAbsolutePath(), new File(httpurl).getName()); if (httpurl.startsWith("http")) image_type = "URL"; else { CompressPic.CompressPic(httpurl, target1.getAbsolutePath(), "");//压缩后的图片 image_type = "BASE64"; httpurl = Base64Util.encode(image2byte(target1.getAbsolutePath())); } map.put("image", httpurl); map.put("image_type", image_type); // map.put("face_field",""); // map.put("option","GATE"); list.add(map); String param = GsonUtils.toJson(list); // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = getAuth(); String result1 = HttpUtil.post(url, accessToken, "application/json", param); JSONObject jsonObject = new JSONObject(result1); String error_msg = jsonObject.optString("error_msg"); JSONObject result = jsonObject.optJSONObject("result"); if (error_msg.equals("SUCCESS")) { double face_liveness = result.optDouble("face_liveness", 0.00);//活体分数值 JSONArray face_list = result.optJSONArray("face_list"); JSONObject location = face_list.optJSONObject(0).optJSONObject("location"); double rotation = location.optDouble("rotation", 0.0);//竖直方向旋转角度 System.out.println(" face_liveness:" + face_liveness); if (face_liveness > 0.4) { int angel = 0; if (45 < rotation && rotation < 135) {//右向横图,需要旋转270度 System.out.println("旋转270度"); angel = 270; } else if (rotation > -135 && rotation < -45) {//左向横图,需要旋转90度 System.out.println("旋转90度"); angel = 90; } else if (rotation >= -180 && rotation <= -135 || rotation >= 135 && rotation <= 180) {//倒向图片,需要旋转180度 System.out.println("旋转180度"); angel = 180; } System.out.println("图片检验成功"); FileUtils.getInstance().writeLogs("检测成功:" + imgFilePath, FileUtils.checkSuc); //E:\wwwhtdocs\SmartCampus\face17e50\School //http://campus.myjxt.com//face17e5/School861/Student/GBZX20171134.jpg //F:\wwwroot\smartcampus\face17e5 // imgFilePath =httpurl.replace("http://campus.myjxt.com","E:\\wwwhtdocs\\SmartCampus"); // imgFilePath = httpurl.replace("http://60.190.202.57:1000","F:\\wwwroot\\smartcampus"); // System.out.println("图片是否存在:" + imgFilePath); if (angel != 0) ImageUtils.rotatePhonePhoto(imgFilePath, angel); return true; } else { FileUtils.getInstance().writeLogs("检测失败,活体分数:" + face_liveness + " " + imgFilePath, FileUtils.checkFail); System.out.println("图片不合格" + imgFilePath); deleteImgFile(imgFilePath); return false; } } else { System.out.println("检测失败"); FileUtils.getInstance().writeLogs("检测失败:" + error_msg + imgFilePath, FileUtils.checkFail); deleteImgFile(imgFilePath); return false; } } catch (Exception e) { e.printStackTrace(); } return true; } private boolean deleteImgFile(String imgFilePath) { imgFilePath = imgFilePath.replace("http://campus.myjxt.com", "E:\\wwwhtdocs\\SmartCampus"); File file = new File(imgFilePath); if (file.exists()) { return file.delete(); } return false; } //图片到byte数组 public byte[] image2byte(String path) { byte[] data = null; FileImageInputStream input = null; try { input = new FileImageInputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); } catch (IOException ex1) { ex1.printStackTrace(); } return data; } /** * 获取权限token * * @return 返回示例: * { * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", * "expires_in": 2592000 * } */ public String getAuth() { // 官网获取的 API Key 更新为你注册的 String clientId = "u6rV4YxRZmwzKj56N0DCW8eO"; // 官网获取的 Secret Key 更新为你注册的 String clientSecret = "Krp3KhmIBdnNEsRa1LavMHuZl0KhQGVm"; 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> 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 = 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; } @RequestMapping(value = "tranpic", method = RequestMethod.GET) @ApiOperation("旋转图片") public void tranPic(@RequestParam("path") String httpurl) { // 请求url String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify"; try { File filePath = new File(httpurl); File[] files = filePath.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; List list = new ArrayList(); Map map = new HashMap<>(); String image_type = ""; httpurl = file.getAbsolutePath(); File target = new File("./huoti/"); if (!target.exists()) target.mkdirs(); File target1 = new File(target.getAbsolutePath(), file.getName()); if (httpurl.startsWith("http")) image_type = "URL"; else { CompressPic.CompressPic(httpurl, target1.getAbsolutePath(), "");//压缩后的图片 image_type = "BASE64"; httpurl = Base64Util.encode(image2byte(target1.getAbsolutePath())); } map.put("image", httpurl); map.put("image_type", image_type); list.add(map); String param = GsonUtils.toJson(list); // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = getAuth(); String result1 = HttpUtil.post(url, accessToken, "application/json", param); JSONObject jsonObject = new JSONObject(result1); String error_msg = jsonObject.optString("error_msg"); JSONObject result = jsonObject.optJSONObject("result"); if (error_msg.equals("SUCCESS")) { double face_liveness = result.optDouble("face_liveness", 0.00);//活体分数值 JSONArray face_list = result.optJSONArray("face_list"); JSONObject location = face_list.optJSONObject(0).optJSONObject("location"); double rotation = location.optDouble("rotation", 0.0);//竖直方向旋转角度 System.out.println(" face_liveness:" + face_liveness); if (face_liveness > 0.4) { int angel = 0; if (45 < rotation && rotation < 135) {//右向横图,需要旋转270度 System.out.println("旋转270度"); angel = 270; } else if (rotation > -135 && rotation < -45) {//左向横图,需要旋转90度 System.out.println("旋转90度"); angel = 90; } else if (rotation >= -180 && rotation <= -135 || rotation >= 135 && rotation <= 180) {//倒向图片,需要旋转180度 System.out.println("旋转180度"); angel = 180; } System.out.println("图片检验成功"); FileUtils.getInstance().writeLogs("检测成功:" + httpurl, FileUtils.checkSuc); System.out.println("files:" + file.getAbsolutePath()); ImageUtils.rotatePhonePhoto(file.getAbsolutePath(), angel); } else { FileUtils.getInstance().writeLogs("检测失败,活体分数:" + face_liveness + " " + httpurl, FileUtils.checkFail); System.out.println("图片不合格" + target1); deleteImgFile(file.getAbsolutePath()); } } else { System.out.println("检测失败"); FileUtils.getInstance().writeLogs("检测失败:" + error_msg + httpurl, FileUtils.checkFail); deleteImgFile(file.getAbsolutePath()); } } } catch (Exception e) { e.printStackTrace(); } } // @RequestMapping(value = "deleteFace", method = RequestMethod.GET) // @ApiOperation("删除人脸") // public void deleteFace(@RequestParam("cardNum") String cardNum, @RequestParam("deviceId") String deviceId) { // // sendUserInfoTask.deleteFace(cardNum, deviceId); // // } @RequestMapping(value = "FaceSearch", method = RequestMethod.POST) @ApiOperation("人脸搜索") public String FaceSearch(@RequestPart("file")MultipartFile file) { // 请求url String url = "https://aip.baidubce.com/rest/2.0/face/v3/search"; try { Map map = new HashMap<>(); map.put("image", Base64Util.encode(file.getBytes())); map.put("liveness_control", "NORMAL"); map.put("group_id_list", "One"); map.put("image_type", "BASE64"); map.put("quality_control", "NORMAL"); String param = GsonUtils.toJson(map); // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = getAuth(); String result = HttpUtil.post(url, accessToken, "application/json", param); System.out.println(result); return result; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "movePic", method = RequestMethod.GET) @ApiOperation("转移下发失败的图片到批量图片库") public void movePic(@RequestParam("schoolId") int schoolId, @RequestParam("userType") int usertype, @RequestParam("deviceId") String deviceId) { sendUserInfoTask.movePic(schoolId, usertype, deviceId); } @RequestMapping(value = "startListener", method = RequestMethod.GET) @ApiOperation("开启监听") public void startListener() { myTasks.reloadPic(); } @RequestMapping(value = "compic", method = RequestMethod.GET) @ApiOperation("图片压缩") @ApiImplicitParam(value = "图片文件目录", name = "filePath") public void compic(@RequestParam("filePath") String httpurl) { try { File filePath = new File(httpurl); File[] files = filePath.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.exists() && !file.getAbsolutePath().contains(".db")) { System.out.println("file:" + file.getAbsolutePath()); String fileName = file.getName().split("\\.")[0] + ".png"; File fileCom = new File(httpurl + "com"); if (!fileCom.exists()) fileCom.mkdirs(); File target = new File(fileCom.getAbsolutePath(), fileName); System.out.println("target:" + target.getAbsolutePath()); CompressPic.CompressPic(file.getAbsolutePath(), target.getAbsolutePath(), "");//压缩后的图片 } } } catch (Exception e) { e.printStackTrace(); } } @RequestMapping(value = "translatePic", method = RequestMethod.POST) @ApiOperation("图片转文字") public String translatePic(@RequestPart MultipartFile file) { try { InputStream inputStream = file.getInputStream(); File fileOut = new File("C:/tran/"); if (!fileOut.exists()) fileOut.mkdirs(); File fileImg = new File(fileOut, System.currentTimeMillis() + ".png"); if (!fileImg.exists())fileImg.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(fileImg); byte[] bytes = new byte[1024]; int length = 0; while ((length = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, length); } inputStream.close(); fileOutputStream.close(); return getAnswer(fileImg.getAbsolutePath(), 2); } catch (IOException e) { e.printStackTrace(); } return "解析失败"; } private String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+AuthService.getAuth(); // + AuthService.getAuth(); private String getAnswer(String imgUrl, int type) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap multiValueMap = new LinkedMultiValueMap<>(); if (type == 1) { multiValueMap.add("url", imgUrl); } else if (type == 2) { multiValueMap.add("image", Base64Util.encode(image2byte(imgUrl))); } HttpEntity requestEntity = new HttpEntity(multiValueMap, headers); ResponseEntity result = restTemplate.postForEntity(url, requestEntity, String.class); JSONObject jsonObject = null; try { jsonObject = new JSONObject(result.getBody()); } catch (JSONException e) { e.printStackTrace(); } // System.out.println("result:"+result.getBody()); JSONArray words_result = jsonObject.optJSONArray("words_result"); // System.out.println("words_result:"+words_result); StringBuilder stringBuilder = new StringBuilder(); if (words_result != null) { for (int i = 0; i < words_result.length(); i++) { String words = words_result.optJSONObject(i).optString("words"); stringBuilder.append(words + " "); } System.out.println("result:" + stringBuilder.toString()); } return stringBuilder.toString().equals("") ? "" : stringBuilder.toString(); } }