80 lines
2.5 KiB
Java
80 lines
2.5 KiB
Java
package com.zyh.common.face;
|
|
|
|
import com.baidu.aip.util.Base64Util;
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.net.URL;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
public class FaceMatchUtil {
|
|
|
|
public static float matchImages(String imageUrl1, String imageUrl2) {
|
|
try {
|
|
byte[] bytes1 = readImageFromUrl(imageUrl1);
|
|
byte[] bytes2 = readImageFromUrl(imageUrl2);
|
|
|
|
List<Map<String, Object>> images = new ArrayList<>();
|
|
|
|
Map<String, Object> map1 = createImageMap(Base64Util.encode(bytes1), "IDCARD");
|
|
Map<String, Object> map2 = createImageMap(Base64Util.encode(bytes2), "LIVE");
|
|
|
|
images.add(map1);
|
|
images.add(map2);
|
|
|
|
String param = GsonUtils.toJson(images);
|
|
|
|
String accessToken = GetAccessToken.getAuth();
|
|
|
|
String result = HttpUtil.post("https://aip.baidubce.com/rest/2.0/face/v3/match", accessToken, "application/json", param);
|
|
|
|
return parseScore(result);
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
return 0.0f;
|
|
}
|
|
}
|
|
|
|
private static byte[] readImageFromUrl(String imageUrl) throws IOException {
|
|
URL url = new URL(imageUrl);
|
|
try (InputStream inputStream = url.openStream();
|
|
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
|
|
|
byte[] buffer = new byte[1024];
|
|
int bytesRead;
|
|
|
|
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
|
byteArrayOutputStream.write(buffer, 0, bytesRead);
|
|
}
|
|
|
|
return byteArrayOutputStream.toByteArray();
|
|
}
|
|
}
|
|
|
|
private static Map<String, Object> createImageMap(String image, String faceType) {
|
|
Map<String, Object> map = new HashMap<>();
|
|
map.put("image", image);
|
|
map.put("image_type", "BASE64");
|
|
map.put("face_type", faceType);
|
|
map.put("quality_control", "LOW");
|
|
map.put("liveness_control", "NONE");
|
|
return map;
|
|
}
|
|
|
|
private static float parseScore(String result) {
|
|
try {
|
|
Map<String, Object> resultMap = GsonUtils.fromJson(result, Map.class);
|
|
Map<String, Object> resultData = (Map<String, Object>) resultMap.get("result");
|
|
float score = Float.parseFloat(resultData.get("score").toString());
|
|
return score;
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
return 0.0f;
|
|
}
|
|
}
|
|
}
|