BaiduUtils.java
11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package com.example.dahua.utils;
import com.alibaba.fastjson.JSON;
import com.example.dahua.async.ImageUtils;
import com.example.dahua.lib.CompressPic;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class BaiduUtils {
private static BaiduUtils baiduUtils;
public static BaiduUtils getBaiduUtils(){
if (null==baiduUtils){
synchronized (BaiduUtils.class){
if (null==baiduUtils)baiduUtils=new BaiduUtils();
}
}
return baiduUtils;
}
public boolean checkImg(String httpurl){
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
try {
List list = new ArrayList();
Map<String, String> 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 false;
}
}
/**
* 注册人脸到百度
* @param file
*/
private void addToBaidu(File file) {
//学籍号或者教职工编号
String userCode = file.getName().split("\\.")[0];
// BaiduUtils.getBaiduUtils().addFace(file,)
}
//图片到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;
}
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;
}
/**
* 获取权限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<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.err.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
// System.err.println("result:" + result);
JSONObject jsonObject = 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;
}
//注册人脸
public String addFace(File img, String group_id, String user_id, String userInfo) {
String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
try {
Map<String, Object> map = new HashMap<>();
map.put("image", Base64Util.encode(InputStream2ByteArray(img.getAbsolutePath())));
map.put("group_id", group_id);
map.put("user_id", user_id);
map.put("user_info", userInfo);
// map.put("liveness_control", "NORMAL");
map.put("image_type", "BASE64");
map.put("quality_control", "NORMAL");
String param = GsonUtils.toJson(map);
// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
String result = HttpUtil.post(url, getAuth(), "application/json", param);
System.out.println(result);
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
String error_msg = jsonObject.getString("error_msg");
if (error_msg.equals("SUCCESS")) {
// com.alibaba.fastjson.JSONObject faceResult = jsonObject.getJSONObject("result");
// FacerecordBean facerecordBean = new FacerecordBean();
//
// facerecordBean.setFace_token(faceResult.getString("face_token"));
// facerecordBean.setGroup_id(group_id);
// facerecordBean.setIntime(simpleDateFormat.format(new Date()));
// facerecordBean.setUser_id(user_id);
//
// facerecordService.addFacerecord(facerecordBean);
return "注册成功";
} else {
return error_msg;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private byte[] InputStream2ByteArray(String filePath) throws IOException {
InputStream in = new FileInputStream(filePath);
byte[] data = toByteArray(in);
in.close();
return data;
}
private byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
}