文章目录
- 一、百度智能云
- 1、注册登录
- 2、创建应用
- 3、完成认证领取免费测试资源
- 二、springboot集成
- 1、pom
- 2、配置application.yml
- 3、官方文档
- 三、逻辑分析
- 四、代码
- 1、图片上传
- 2、格式转换
- 3、百度Token获取
- 4、工具类
- 5、实体类
- 6、AI人脸验证
- 7、AI人脸比对
- 8、controller接口
一、百度智能云
1、注册登录
百度智能云地址
在该网站完成注册登录
2、创建应用
3、完成认证领取免费测试资源
二、springboot集成
1、pom
<!--百度AI-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.8.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>5.0.0-alpha.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
2、配置application.yml
baidu:
ai:
appId: 百度平台中创建的应用的AppID
apiKey: 百度平台中创建的应用的API Key
secretKey: 百度平台中创建的应用的Secret key
imageType: BASE64
3、官方文档
参考官方网站说明文档
三、逻辑分析
当用户首次提交自己的人脸模型时逻辑如下:
当用户非首次提交人脸(考勤打卡提交人脸)
四、代码
1、图片上传
@ApiOperation("上传图片")
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile fileUpload){
}
2、格式转换
/*** MultipartFile转成InputStream 将图片转换成Base64编码 */
public static String imgToBase64(MultipartFile uploadFiles) {
InputStream in;
byte[] data = null;
//读取图片字节数组
try {
byte[] byteArr = uploadFiles.getBytes();
in = new ByteArrayInputStream(byteArr);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.getMessage();
e1.printStackTrace();
}
return new String(Objects.requireNonNull(Base64.encodeBase64(data)));
}
3、百度Token获取
package com.buba.wechatsk.face;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* 获取token类
*/
@Service
public class AuthService {
@Value("${baidu.ai.apiKey}")
private final String apiKey;
@Value("${baidu.ai.secretKey}")
private final String secretKey;
/**
* 获取权限token
* @return 返回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public String getAuth() {
// 官网获取的 API Key 更新为你注册的
String clientId = apiKey;
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = secretKey;
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 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;
}
}
4、工具类
/*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
package com.buba.wechatsk.face;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Json工具类.
*/
public class GsonUtils {
private static Gson gson = new GsonBuilder().create();
public static String toJson(Object value) {
return gson.toJson(value);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
return gson.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
return (T) gson.fromJson(json, typeOfT);
}
}
5、实体类
@Data
public class FaceEntity {
private String image;
private String image_type;
private String face_type;
private String quality_control;
private String liveness_control;
}
@Data
public class FaceResultEntity {
private String error_code;
private String error_msg;
private String log_id;
private Integer timestamp;
private Integer cached;
private Map<Object,Object> result;
}
6、AI人脸验证
7、AI人脸比对
package com.buba.wechatsk.face;
import okhttp3.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author qlx
*/
@Component
public class MyFaceAi {
final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
/**
* 人脸对比
*/
public boolean compare(String s1,String s2) throws Exception{
FaceEntity face1 = new FaceEntity();
face1.setImage(s1);
face1.setImage_type("BASE64");
face1.setFace_type("LIVE");
face1.setQuality_control("LOW");
face1.setLiveness_control("LOW");
FaceEntity face2 = new FaceEntity();
face2.setImage(s2);
face2.setImage_type("BASE64");
face2.setFace_type("LIVE");
face2.setQuality_control("LOW");
face2.setLiveness_control("LOW");
List list = new ArrayList();
list.add(face1);
list.add(face2);
String param = GsonUtils.toJson(list);
AuthService authService = new AuthService();
String token = authService.getAuth();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, param);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="+token)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String res = response.body().string();
System.out.println(res);
FaceResultEntity rr = GsonUtils.fromJson(res,FaceResultEntity.class);
Double score = (Double) rr.getResult().get("score");
return score>80?true:false;
}
}
8、controller接口
@Autowired
private JwtUtil jwtUtil;
@Autowired
private MyFaceAi myFaceAi;
@Autowired
private FaceServicefaceService; /**
* 上传
*
* @param fileUpload 图片资源
* @return 图映射的虚拟访问路径
*/
@ApiOperation("上传人脸比对已存在的人脸")
@PostMapping("/upload")
public Result upload(@RequestHeader String token,@RequestParam("file") MultipartFile fileUpload) throws Exception{
// 1、转base64
String currentFace = FileUtil.imgToBase64(fileUpload);
// 2、通过token获取当前用户id
int uid = jwtUtil.getUserId(token);
// 3、通过uid查询数据库中已经存在的该用户注册的人脸base64
String oldFace = faceService.selectFaceByUid(uid);
// 4、比对
boolean b = myFaceAi.compare(currentFace,oldFace);
return Result.ok(b+"");
}