目录
一、百度智能云
二、准备工作
1.百度云注册/登录账号
百度智能云-云智一体深入产业百度智能云致力于为企业和开发者提供全球领先的人工智能、大数据和云计算服务,加速产业智能化转型升级https://cloud.baidu.com/
2.百度云实名认证
3.打开人脸识别控制台
4.应用列表创建应用
5.查看人脸库
6.领取资源(领取免费资源)
每个月1000次的使用机会
二、代码实现
注:由于项目框架和方法不同,所以有些代码需要你们根据自己项目进行更改。
1.加依赖
<!-- 人脸识别 jdk-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.7</version>
</dependency>
2.添加配置
#百度人脸识别配置
baidu:
face:
appId: ""
apiKey: ""
secretKey: ""
imageType: ""
grouping: ""
每个参数如何填写
(1)appId,apiKey,secretKey
(2)imageType
上传的图片有两种格式,可以根据需求来
url地址
表示图片数据是通过 URL 地址传输的。这通常意味着您不直接上传图片,而是提供一个指向图片的在线链接,百度API将从该URL获取图片并处理。(URL图片路径必须是要用浏览器的公网资源)
Base64字符串形式
请求的图片需经过Base64编码,图片的base64编码指将图片数据编码成一串字符串,使用该字符串代替图像地址。您可以首先得到图片的二进制,然后用Base64格式编码即可。需要注意的是,图片的base64编码是不包含图片头的,如data:image/jpg;base64,编码后的图片大小不超过2M;(用于上传本地图片)
(3)grouping
3.后台(Java)代码的实现
(1)创建初始化对象
import com.baidu.aip.face.AipFace;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* BaiduFaceApi类封装了与百度人脸识别API的交互,
* 提供了初始化人脸识别客户端并执行人脸注册的功能。
*/
@Configuration
@Data
public class BaiduFaceApi {
/**
* 百度人脸识别API的App ID,配置文件中注入。
* 使用该App ID进行API请求验证。
*/
@Value("${baidu.face.appId}")
private String appId;
/**
* 百度人脸识别API的API Key,配置文件中注入。
* 用于身份验证和访问授权。
*/
@Value("${baidu.face.apiKey}")
private String apiKey;
/**
* 百度人脸识别API的Secret Key,配置文件中注入。
* 用于加密签名,确保API请求的安全性。
*/
@Value("${baidu.face.secretKey}")
private String secretKey;
/**
* 创建并返回一个初始化后的AipFace实例。
* 使用从配置文件中注入的APP_ID、API_KEY和SECRET_KEY。
*
* @return 初始化后的AipFace实例
*/
@Bean
public AipFace getAipFace() {
/*
* 创建并初始化AipFace实例:
* 使用配置文件中提供的App ID、API Key和Secret Key进行身份验证。
* 该实例用于与百度人脸识别API进行后续的交互。
*/
// 初始化AipFace实例
return new AipFace(appId, apiKey, secretKey);
}
}
(2)业务流程代码
第一种:当imageType选择使用URL形式的时候
a.创建util工具类
import com.baidu.aip.face.AipFace;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Component
public class BaiduFaceUtil {
@Value("${baidu.face.imageType}")
public String imageType;
@Value("${baidu.face.grouping}")
public String grouping;
@Autowired
private AipFace aipFace;
/**
* 执行人脸注册操作,将图片与用户ID关联。
* <p>
* 此方法将上传图片并通过百度人脸识别API将其与指定的用户ID关联。
* 主要用于用户人脸信息的注册或更新。
* </p>
*
* @param imageFilePath 图片的路径
* @param userId 用户的唯一标识ID
* @return 调用百度API后返回的结果字符串
* @throws RuntimeException 当上传文件失败或API调用异常时抛出
*/
public String registerFace(String imageFilePath, String userId) {
// 检查输入参数是否有效
if (StringUtils.isBlank(imageFilePath)) {
throw new RuntimeException("您还没有选择图片!"); // 图片路径为空时抛出异常
}
try {
/*
* 配置百度人脸识别API的可选参数。
* 这些参数用于定制注册过程中的一些特性,例如图像质量控制、活体检测等。
*/
HashMap<String, String> apiOptions = new HashMap<>();
// 用户信息:可以为每个用户设置额外的信息,用于区分不同用户。
apiOptions.put("user_info", "user's info"); // 例如用户名、电话等。
// 质量控制:设置为 NORMAL,表示对图像质量要求不高。
apiOptions.put("quality_control", "NORMAL");
// 活体控制:设置为 NONE,表示不进行活体检测,适用于一些不需要活体检测的场景。
apiOptions.put("liveness_control", "NONE");
// 动作类型:设置为 REPLACE,表示若该用户已存在,则用新的照片信息替换原有信息。
apiOptions.put("action_type", "REPLACE");
/*
* 调用百度人脸 API 的 addUser 方法进行人脸注册。
* 传入参数包括:图片路径、图片类型、分组信息、用户ID 及额外的可选参数。
*/
JSONObject apiResponse = aipFace.addUser(imageFilePath, imageType, grouping, userId, apiOptions);
/*
* 返回注册结果中的信息。
* 响应 JSON 中包含了注册操作的结果。
* 通过获取 "result" 字段,提取并返回成功与否的状态。
*/
return apiResponse.get("result").toString(); // 返回操作结果的字符串表示
} catch (Exception e) {
// 捕获异常并抛出自定义异常消息,便于调试和排查问题
throw new RuntimeException("上传文件失败,服务器发生异常!", e); // 抛出异常,附带详细错误信息
}
}
/**
* 登录人脸操作,根据提供的图片文件进行人脸识别并返回匹配的用户ID。
*
* @param file 人脸图像的路径,图像为Base64编码字符串
* @return 匹配的用户ID,如果没有匹配的用户则抛出异常
*/
public Long faceLogin(String file) {
// 创建一个 HashMap 用于设置可选参数,所有参数都会传递给人脸识别 API
HashMap<String, Object> options = new HashMap<>();
// 设置最大人脸数量为 3,表示最多检测 3 张人脸
options.put("max_face_num", "3");
// 设置匹配阈值为 80,表示只有匹配度大于或等于 80% 的用户才会被认为匹配
options.put("match_threshold", "80");
// 设置图像质量控制为 NORMAL,表示图像质量控制较为宽松
options.put("quality_control", "NORMAL");
// 设置活体检测为 NONE,表示不进行活体检测
options.put("liveness_control", "NONE");
// 设置最多返回 3 个用户,表示只返回最匹配的 3 个用户
options.put("max_user_num", "3");
try {
/* 调用百度人脸识别的多用户人脸搜索接口 */
// 通过百度人脸 API 的 multiSearch 方法发送请求,获取返回的 JSON 数据
// file: 人脸图像的 Base64 编码字符串
// imageType: 图像类型,可能是 BASE64 或 URL
// grouping: 分组名,用于限制搜索范围
// options: 上述设置的可选参数
JSONObject res = aipFace.multiSearch(file, imageType, grouping, options);
/* 解析接口返回的 JSON 数据 */
// 获取返回的结果对象 "result"
JSONObject result = res.optJSONObject("result");
if (result == null) {
// 如果返回的结果为空,抛出异常
throw new RuntimeException("人脸识别接口返回的结果为空");
}
// 获取人脸列表(face_list),该列表包含识别到的所有人脸信息
JSONArray faceList = result.optJSONArray("face_list");
if (faceList == null || faceList.length() == 0) {
// 如果没有检测到人脸数据,抛出异常
throw new RuntimeException("未检测到人脸,或人脸数据为空");
}
/* 获取第一个人脸的匹配用户列表 */
// 取出检测到的第一个人脸对象
JSONObject firstFace = faceList.getJSONObject(0);
// 获取该人脸的匹配用户列表(user_list),该列表包含与该人脸匹配的用户信息
JSONArray userList = firstFace.optJSONArray("user_list");
if (userList == null || userList.length() == 0) {
// 如果没有找到匹配的用户,抛出异常
throw new RuntimeException("未找到匹配的用户");
}
// 获取匹配用户的第一个 user_id
long userId = userList.getJSONObject(0).optLong("user_id", -1);
if (userId == -1) {
// 如果未能获取到有效的 user_id,抛出异常
throw new RuntimeException("未获取到有效的 user_id");
}
// 返回匹配的第一个用户的 user_id
return userId;
} catch (Exception e) {
/* 捕获异常并抛出详细的错误信息,便于调试 */
throw new RuntimeException("人脸登录失败,错误信息:" + e.getMessage(), e);
}
}
}
b.service方法
import com.medical.system.domain.SysUser;
import org.springframework.web.multipart.MultipartFile;
/**
* @author cmh
* @class SysLoginServices
* @description 描述
* @date 2025/1/6 10:06
*/
public interface SysLoginService {
/**
* 人脸识别登录
*
* @param file 用户上传的图片文件
* @return 返回登录的用户信息
*/
SysUser faceLogin(MultipartFile file);
/**
* 人脸注册
*
* @param file 用户上传的图片文件
* @param id 用户的唯一标识
* @return 注册结果(如成功/失败消息)
*/
String registered(MultipartFile file, String id);
}
c.service实现类
import com.medical.auth.util.BaiduFaceUtil;
import com.medical.common.core.domain.Result;
import com.medical.file.remote.RemoteFileService;
import com.medical.system.domain.SysUser;
import com.medical.system.remote.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author cmh
* @class SysLoginServiceImpl
* @description 描述
* @date 2025/1/6 9:40
*/
@Service
public class SysLoginServiceImpl extends SysLoginService{
@Autowired
private BaiduFaceUtil baiduFaceUtil;
@Autowired
private RemoteFileService remoteFileService;
@Autowired
private RemoteUserService remoteUserService;
/**
* 人脸识别登录
*
* @param file 用户上传的图片文件
* @return 返回登录的用户信息
*/
@Override
public SysUser faceLogin(MultipartFile file) {
// 上传文件并获取文件 URL
String imageUrl = uploadFileAndGetUrl(file);
// 调用百度人脸识别接口进行登录验证
Long userId = baiduFaceUtil.faceLogin(imageUrl);
// 根据用户 ID 获取用户信息
Result<SysUser> userResult = remoteUserService.getUserInfo(userId);
// 返回用户信息
return userResult.getData();
}
/**
* 人脸注册
*
* @param file 用户上传的图片文件
* @param id 用户的唯一标识
* @return 注册结果(如成功/失败消息)
*/
@Override
public String registered(MultipartFile file, String id) {
// 上传文件并获取文件 URL
String imageUrl = uploadFileAndGetUrl(file);
// 调用百度人脸识别接口进行注册
return baiduFaceUtil.registerFace(imageUrl, id);
}
/**
* 上传图片并获取文件 URL
*
* @param file 用户上传的图片文件
* @return 上传后的文件 URL
*/
private String uploadFileAndGetUrl(MultipartFile file) {
// 上传图片文件并返回文件的 URL 地址
return remoteFileService.uploadFilePerson(file).getData().getUrl();
}
}
注:其中remoteFileService.uploadFilePerson(file).getData().getUrl();和Result userResult = remoteUserService.getUserInfo(userId);是我自己封装的上传图片和查询用户信息的方法,需要自己根据自己的项目以及需求进行更改
d.controller调用
import com.medical.auth.service.SysLoginService;
import com.medical.common.core.domain.Result;
import com.medical.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* 人脸识别相关操作的控制器
*/
@RequestMapping("/face")
@RestController
@CrossOrigin
public class FaceController {
@Autowired
private SysLoginService sysLoginService; // 系统登录服务
/**
* 人脸识别登录接口
*
* @param file 上传的图片文件
* @return 登录成功后的用户信息
*/
@PostMapping("/faceLogin")
@ResponseBody
public Result<SysUser> faceLogin(@RequestParam("file") MultipartFile file) {
// 调用 sysLoginService 进行人脸识别登录
SysUser userInfo = sysLoginService.faceLogin(file);
// 返回登录结果
return Result.success(userInfo);
}
/**
* 人脸信息注册接口
*
* @param file 上传的图片文件
* @param id 用户唯一标识
* @return 注册结果
*/
@PostMapping("/registerFace")
@ResponseBody
public Result registered(@RequestParam("file") MultipartFile file,
@RequestParam("id") String id) {
// 调用 sysLoginService 进行人脸注册
String registrationResult = sysLoginService.registered(file, id);
// 返回注册结果
return Result.success(registrationResult);
}
}
第二种:当imageType选择使用BASE64形式的时候
a.创建util工具类
import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
@Component
public class BaiduFaceUtil {
@Value("${baidu.face.imageType}")
public String imageType;
@Value("${baidu.face.grouping}")
public String grouping;
@Autowired
private AipFace aipFace;
/**
* 获取上传图片的Base64编码
*
* @param file 上传的图片文件
* @return 返回图片的Base64编码
*/
public String getImages(MultipartFile file) {
try {
// 校验文件是否为空
if (file == null) {
throw new RuntimeException("您还没有选择图片!");
}
// 获取原始文件名
String originalFileName = file.getOriginalFilename();
// 生成文件名,避免重复文件名
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String fileName = timeStamp + "_" + originalFileName;
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
// 格式化日期 存储文件地址
String dateDirPath = "D:/img/" + currentDate.format(formatter);
// 创建日期文件夹
File dateDir = new File(dateDirPath);
// 如果文件夹不存在,则创建
if (!dateDir.exists() && !dateDir.mkdirs()) {
throw new RuntimeException("创建文件夹失败!");
}
// 创建最终文件路径
File destFile = new File(dateDir, fileName);
// 保存文件到目标路径
file.transferTo(destFile);
// 读取文件并将其转为Base64字符串
byte[] fileContent = Files.readAllBytes(destFile.toPath());
return Base64.getEncoder().encodeToString(fileContent);
} catch (IOException e) {
// 捕获文件上传过程中可能发生的异常
throw new RuntimeException("上传文件失败,服务器发生异常!", e);
}
}
/**
* 执行人脸注册操作,将图片与用户ID关联。
* <p>
* 此方法将上传图片并通过百度人脸识别API将其与指定的用户ID关联。
* 主要用于用户人脸信息的注册或更新。
* </p>
*
* @param imageFilePath 图片文件
* @param userId 用户的唯一标识ID
* @return 调用百度API后返回的结果字符串
* @throws RuntimeException 当上传文件失败或API调用异常时抛出
*/
public String registerFace(MultipartFile imageFilePath, String userId) {
// 检查输入参数是否有效
if (imageFilePath == null) {
throw new RuntimeException("您还没有选择图片!"); // 图片文件为空时抛出异常
}
try {
// 配置百度人脸识别API的可选参数
HashMap<String, String> apiOptions = new HashMap<>();
// 用户信息:可以为每个用户设置额外的信息,用于区分不同用户
apiOptions.put("user_info", "user's info"); // 例如用户名、电话等
// 质量控制:设置为 NORMAL,表示对图像质量要求不高
apiOptions.put("quality_control", "NORMAL");
// 活体控制:设置为 NONE,表示不进行活体检测,适用于一些不需要活体检测的场景
apiOptions.put("liveness_control", "NONE");
// 动作类型:设置为 REPLACE,表示若该用户已存在,则用新的照片信息替换原有信息
apiOptions.put("action_type", "REPLACE");
// 获取上传图片的Base64编码
String imageBase64 = getImages(imageFilePath);
// 调用百度人脸API的addUser方法进行人脸注册
JSONObject apiResponse = aipFace.addUser(imageBase64, imageType, grouping, userId, apiOptions);
// 返回注册结果中的信息
return apiResponse.get("result").toString(); // 返回操作结果的字符串表示
} catch (Exception e) {
// 捕获异常并抛出自定义异常消息,便于调试和排查问题
throw new RuntimeException("上传文件失败,服务器发生异常!", e); // 抛出异常,附带详细错误信息
}
}
/**
* 登录人脸操作,根据提供的图片文件进行人脸识别并返回匹配的用户ID。
*
* @param file 人脸图像的文件
* @return 匹配的用户ID,如果没有匹配的用户则抛出异常
*/
public Long faceLogin(MultipartFile file) {
// 创建一个 HashMap 用于设置可选参数,所有参数都会传递给人脸识别 API
HashMap<String, Object> options = new HashMap<>();
// 设置最大人脸数量为 3,表示最多检测 3 张人脸
options.put("max_face_num", 3);
// 设置匹配阈值为 80,表示只有匹配度大于或等于 80% 的用户才会被认为匹配
options.put("match_threshold", 80);
// 设置图像质量控制为 NORMAL,表示图像质量控制较为宽松
options.put("quality_control", "NORMAL");
// 设置活体检测为 NONE,表示不进行活体检测
options.put("liveness_control", "NONE");
// 设置最多返回 3 个用户,表示只返回最匹配的 3 个用户
options.put("max_user_num", 3);
// 获取上传图片的Base64编码
String imageBase64 = getImages(file);
try {
// 调用百度人脸识别的多用户人脸搜索接口
JSONObject response = aipFace.multiSearch(imageBase64, imageType, grouping, options);
// 获取返回的结果对象 "result"
JSONObject result = response.optJSONObject("result");
if (result == null) {
throw new RuntimeException("人脸识别接口返回的结果为空");
}
// 获取人脸列表(face_list),该列表包含识别到的所有人脸信息
JSONArray faceList = result.optJSONArray("face_list");
if (faceList == null || faceList.length() == 0) {
throw new RuntimeException("未检测到人脸,或人脸数据为空");
}
// 获取第一个人脸的匹配用户列表
JSONObject firstFace = faceList.getJSONObject(0);
JSONArray userList = firstFace.optJSONArray("user_list");
if (userList == null || userList.length() == 0) {
throw new RuntimeException("未找到匹配的用户");
}
// 获取匹配用户的第一个 user_id
long userId = userList.getJSONObject(0).optLong("user_id", -1);
if (userId == -1) {
throw new RuntimeException("未获取到有效的 user_id");
}
// 返回匹配的第一个用户的 user_id
return userId;
} catch (Exception e) {
// 捕获异常并抛出详细的错误信息,便于调试
throw new RuntimeException("人脸登录失败,错误信息:" + e.getMessage(), e);
}
}
}
b.service方法
import com.medical.system.domain.SysUser;
import org.springframework.web.multipart.MultipartFile;
/**
* @author cmh
* @class SysLoginServices
* @description 描述
* @date 2025/1/6 10:06
*/
public interface SysLoginService {
/**
* 人脸识别登录
*
* @param file 用户上传的图片文件
* @return 返回登录的用户信息
*/
SysUser faceLogin(MultipartFile file);
/**
* 人脸注册
*
* @param file 用户上传的图片文件
* @param id 用户的唯一标识
* @return 注册结果(如成功/失败消息)
*/
String registered(MultipartFile file, String id);
}
c.service实现类
import com.medical.auth.util.BaiduFaceUtil;
import com.medical.common.core.domain.Result;
import com.medical.system.domain.SysUser;
import com.medical.system.remote.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author cmh
* @class impl
* @description 描述
* @date 2025/1/6 11:17
*/
@Service
public class SysLoginServiceImpl extends SysLoginService{
@Autowired
private RemoteUserService remoteUserService;
@Autowired
private BaiduFaceUtil baiduFaceUtil;
/**
* 人脸识别登录
*
* @param file 图片文件
* @return 返回登录的用户信息
*/
public SysUser faceLogin(MultipartFile file) {
// 调用百度人脸识别接口进行登录验证,获取用户ID
Long userId = baiduFaceUtil.faceLogin(file);
// 根据用户ID获取用户信息
Result<SysUser> userResult = remoteUserService.getUserInfo(userId);
// 返回用户信息
return userResult.getData();
}
/**
* 人脸注册
*
* @param file 图片文件
* @param id 用户的唯一标识
* @return 注册结果(如成功/失败消息)
*/
public String registered(MultipartFile file, String id) {
// 调用百度人脸识别接口进行注册
return baiduFaceUtil.registerFace(file, id);
}
}
注:其中Result userResult = remoteUserService.getUserInfo(userId);是我自己封装的查询用户信息的方法,需要自己根据自己的项目以及需求进行更改
d.controller调用
import com.medical.auth.service.SysLoginService;
import com.medical.common.core.domain.Result;
import com.medical.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* 人脸识别相关操作的控制器
*/
@RequestMapping("/face")
@RestController
@CrossOrigin
public class FaceController {
@Autowired
private SysLoginService sysLoginService; // 系统登录服务
/**
* 人脸识别登录接口
*
* @param file 上传的图片文件
* @return 登录成功后的用户信息
*/
@PostMapping("/faceLogin")
@ResponseBody
public Result<SysUser> faceLogin(@RequestParam("file") MultipartFile file) {
// 调用 sysLoginService 进行人脸识别登录
SysUser userInfo = sysLoginService.faceLogin(file);
// 返回登录结果
return Result.success(userInfo);
}
/**
* 人脸信息注册接口
*
* @param file 上传的图片文件
* @param id 用户唯一标识
* @return 注册结果
*/
@PostMapping("/registerFace")
@ResponseBody
public Result registered(@RequestParam("file") MultipartFile file,
@RequestParam("id") String id) {
// 调用 sysLoginService 进行人脸注册
String registrationResult = sysLoginService.registered(file, id);
// 返回注册结果
return Result.success(registrationResult);
}
}
两种区别
其实对于两种类型来,就是处理图片的方式不一样罢了,个人比较推荐第一种,方便后期如果想记录日志的话或其他处理都是比较方便的,上传到本地不好进行操作。其次如果部署的话,第一种不需要改,第二种需要把图片存储地址改了,不然会出现路径找不到的问题。
4.前台(Vue)代码实现
注:有些路径的跳转需要自己改和实现,毕竟项目结构和方法不一样
(1)注册人脸代码
<template>
<div id="aaa">
<h1>人脸信息注册</h1>
<video
id="videoCamera"
:width="videoWidth"
:height="videoHeight"
:x5-video-player-fullscreen="true"
autoplay
></video>
<canvas
style="display: none"
id="canvasCamera"
:width="videoWidth"
:height="videoHeight"
></canvas>
<br>
<el-button type="primary" plain @click="setImage()">手动拍照</el-button>
<p class="fail_tips"></p>
</div>
</template>
<script>
import {registered} from "@/api/face/face";
export default {
data() {
return {
id: localStorage.getItem('user_id'),
// 视频调用相关数据开始
videoWidth: 500,
videoHeight: 400,
imgSrc: "",
thisCancas: null,
thisContext: null,
thisVideo: null,
openVideo: false,
};
},
mounted() {
// 第一步:在组件挂载完成后打开摄像头
this.getCompetence(); // 调用摄像头权限方法
},
methods: {
// 第三步和第四步:拍照后将图片转换为 file 格式并上传,获取图片 URL 链接
async postImg() {
let formData = new FormData(); // 创建 FormData 对象用于存储表单数据
formData.append("file", this.base64ToFile(this.imgSrc, "png")); // 将 base64 格式的图片转换为 file 并添加到表单数据中
formData.append("flag", "videoImg"); // 添加额外参数,标识图片来源
// 使用 axios 调用后台上传图片接口
await registered(formData, this.id).then(result => {
console.log(result.data); // 打印接口返回的数据
if (result.data.data != "null") { // 如果返回的数据不为空
this.$message({ // 显示成功消息
message: "上传成功",
type: "success",
center: true,
showClose: true,
});
this.$router.push("/user/profile"); // 跳转到用户资料页面
} else {
this.$message({ // 显示失败消息
message: "上传失败,图像不合格",
center: true,
type: "error",
showClose: true,
});
}
})
},
// 调用权限(打开摄像头功能)
getCompetence() {
var _this = this; // 保存 this 指针的引用,以便在回调函数中使用
_this.thisCancas = document.getElementById("canvasCamera"); // 获取 canvas 元素
_this.thisContext = this.thisCancas.getContext("2d"); // 获取 canvas 的 2D 绘图上下文
_this.thisVideo = document.getElementById("videoCamera"); // 获取 video 元素
_this.thisVideo.style.display = "block"; // 显示 video 元素
// 获取媒体属性,旧版本浏览器可能不支持 mediaDevices,我们首先设置一个空对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// 一些浏览器实现了部分 mediaDevices,我们不能只分配一个对象
// 使用 getUserMedia,因为它会覆盖现有的属性。
// 这里,如果缺少 getUserMedia 属性,就添加它。
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// 首先获取现存的 getUserMedia(如果存在)
var getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.getUserMedia;
// 有些浏览器不支持,会返回错误信息
// 保持接口一致
if (!getUserMedia) {
// 不存在则报错
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
// 否则,使用 Promise 将调用包装到旧的 navigator.getUserMedia
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
var constraints = {
audio: false, // 不请求音频权限
video: {
width: this.videoWidth, // 设置视频流的宽度
height: this.videoHeight, // 设置视频流的高度
transform: "scaleX(-1)", // 水平翻转视频流,使镜像效果更自然
},
};
navigator.mediaDevices
.getUserMedia(constraints) // 请求摄像头权限
.then(function (stream) {
// 旧的浏览器可能没有 srcObject
if ("srcObject" in _this.thisVideo) {
_this.thisVideo.srcObject = stream; // 设置 video 元素的源对象为摄像头流
} else {
// 避免在新的浏览器中使用它,因为它正在被弃用。
_this.thisVideo.src = window.URL.createObjectURL(stream); // 创建一个指向摄像头流的 URL 并设置为 video 元素的源
}
_this.thisVideo.onloadedmetadata = function (e) {
_this.thisVideo.play(); // 当视频流加载完成后开始播放
};
})
.catch((err) => {
console.log(err); // 如果请求摄像头权限失败则打印错误信息
});
},
// 第二步:绘制图片(拍照功能)
setImage() {
var _this = this; // 保存 this 指针的引用,以便在回调函数中使用
// canvas 画图
_this.thisContext.drawImage(_this.thisVideo, 0, 0); // 在 canvas 上绘制视频流的当前帧
// 获取图片 base64 链接
var image = this.thisCancas.toDataURL("image/png"); // 将 canvas 上的图像转换为 base64 编码的 PNG 图片
_this.imgSrc = image; // 赋值并预览图片
// 这里是调用上传图片接口=====
this.postImg(); // 绘制完图片后调用图片上传接口
},
// 关闭摄像头
stopNavigator() {
this.thisVideo.srcObject.getTracks()[0].stop(); // 停止视频流的轨道,关闭摄像头
},
// base64 转为 file
base64ToFile(urlData, fileName) {
let arr = urlData.split(","); // 将 base64 字符串分割为两部分,前半部分是 MIME 类型,后半部分是 base64 编码的数据
let mime = arr[0].match(/:(.*?);/)[1]; // 提取 MIME 类型
let bytes = atob(arr[1]); // 解码 base64
let n = bytes.length;
let ia = new Uint8Array(n); // 创建一个 Uint8Array 数组来存储解码后的字节数据
while (n--) {
ia[n] = bytes.charCodeAt(n); // 将每个字符的 ASCII 码转换为对应的字节值并存储到数组中
}
return new File([ia], fileName, {type: mime}); // 使用解码后的字节数据、文件名和 MIME 类型创建一个 File 对象并返回
},
},
destroyed: function () {
// 离开当前页面时
this.stopNavigator(); // 关闭摄像头
},
};
</script>
<style>
.result_img {
width: 226px;
height: 195px;
background: #d8d8d8;
position: absolute;
top: 100px;
right: -100px;
}
#aaa {
width: 500px;
text-align: center;
margin: auto;
position: relative;
}
</style>
(2)人脸登录代码
<template>
<div id="bbb">
<router-view></router-view>
<h1>人脸登录</h1>
<video
id="videoCamera"
:width="videoWidth"
:height="videoHeight"
:x5-video-player-fullscreen="true"
autoplay
></video>
<canvas
style="display: none"
id="canvasCamera"
:width="videoWidth"
:height="videoHeight"
></canvas>
<br>
<el-button type="primary" plain @click="setImage()">手动拍照</el-button>
</div>
</template>
<script>
import Cookies from 'js-cookie'
import { faceLogin } from '../api/face/face'
export default {
name: 'FaceIndex',
data() {
return {
// 视频调用相关数据开始
videoWidth: 500,
videoHeight: 400,
imgSrc: '',
thisCancas: null,
thisContext: null,
thisVideo: null,
openVideo: false,
loginForm: {
username: '',
password: '',
rememberMe: false,
code: '',
uuid: '',
typeStatus: 1
}
}
},
mounted() {
// 在组件挂载完成后,打开摄像头
this.getCompetence(); // 调用摄像头权限方法
},
methods: {
// 第三步和第四步:拍照后将图片转换为 file 格式并上传,获取图片 URL 链接
async postImg() {
let formData = new FormData(); // 创建 FormData 对象用于存储表单数据
formData.append('file', this.base64ToFile(this.imgSrc, 'png')); // 将 base64 格式的图片转换为 file 并添加到表单数据中
formData.append('flag', 'videoImg'); // 添加额外参数,标识图片来源
// 使用 axios 调用后台上传图片接口
let result = await faceLogin(formData); // 调用登录接口
console.log(result); // 打印接口返回的结果
if (result.code == 200) { // 如果登录成功
this.loginForm.username = result.data.userName; // 设置用户名
this.loginForm.password = result.data.password; // 设置密码
//登录逻辑或方法
//这里调用的是若依又有等登录方法,得调用根据自己项目的登录方法
// this.$store.dispatch('Login', this.loginForm).then(() => { // 调用 Vuex 的 Login action 进行登录
// this.$router.push({ path: this.redirect || '/' }).catch(() => {}); // 登录成功后跳转到指定路径
// });
} else {
this.$message({ // 显示错误消息
message: '登录失败,图像不合格',
center: true,
type: 'error',
showClose: true
});
}
return false; // 返回 false 防止表单默认提交
},
// 调用权限(打开摄像头功能)
getCompetence() {
var _this = this; // 保存 this 指针的引用
_this.thisCancas = document.getElementById('canvasCamera'); // 获取 canvas 元素
_this.thisContext = this.thisCancas.getContext('2d'); // 获取 canvas 的 2D 绘图上下文
_this.thisVideo = document.getElementById('videoCamera'); // 获取 video 元素
_this.thisVideo.style.display = 'block'; // 显示 video 元素
// 获取媒体属性,旧版本浏览器可能不支持 mediaDevices,我们首先设置一个空对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// 一些浏览器实现了部分 mediaDevices,我们不能只分配一个对象
// 使用 getUserMedia,因为它会覆盖现有的属性。
// 这里,如果缺少 getUserMedia 属性,就添加它。
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
// 首先获取现存的 getUserMedia(如果存在)
var getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.getUserMedia;
// 有些浏览器不支持,会返回错误信息
// 保持接口一致
if (!getUserMedia) {
// 不存在则报错
return Promise.reject(
new Error('getUserMedia is not implemented in this browser')
);
}
// 否则,使用 Promise 将调用包装到旧的 navigator.getUserMedia
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
var constraints = {
audio: false, // 不请求音频权限
video: {
width: this.videoWidth, // 设置视频流的宽度
height: this.videoHeight, // 设置视频流的高度
transform: 'scaleX(-1)' // 水平翻转视频流,使镜像效果更自然
}
};
navigator.mediaDevices
.getUserMedia(constraints) // 请求摄像头权限
.then(function(stream) {
// 旧的浏览器可能没有 srcObject
if ('srcObject' in _this.thisVideo) {
_this.thisVideo.srcObject = stream; // 设置 video 元素的源对象为摄像头流
} else {
// 避免在新的浏览器中使用它,因为它正在被弃用。
_this.thisVideo.src = window.URL.createObjectURL(stream); // 创建一个指向摄像头流的 URL 并设置为 video 元素的源
}
_this.thisVideo.onloadedmetadata = function(e) {
_this.thisVideo.play(); // 当视频流加载完成后开始播放
};
})
.catch((err) => {
console.log(err); // 如果请求摄像头权限失败则打印错误信息
});
},
// 第二步:绘制图片(拍照功能)
setImage() {
var _this = this; // 保存 this 指针的引用
// canvas 画图
_this.thisContext.drawImage(_this.thisVideo, 0, 0); // 在 canvas 上绘制视频流的当前帧
// 获取图片 base64 链接
var image = this.thisCancas.toDataURL('image/png'); // 将 canvas 上的图像转换为 base64 编码的 PNG 图片
_this.imgSrc = image; // 赋值并预览图片
// 调用上传图片接口
this.postImg(); // 绘制完图片后调用图片上传接口
},
// 关闭摄像头
stopNavigator() {
this.thisVideo.srcObject.getTracks()[0].stop(); // 停止视频流的轨道,关闭摄像头
},
// base64 转为 file
base64ToFile(urlData, fileName) {
let arr = urlData.split(','); // 将 base64 字符串分割为两部分
let mime = arr[0].match(/:(.*?);/)[1]; // 提取 MIME 类型
let bytes = atob(arr[1]); // 解码 base64
let n = bytes.length;
let ia = new Uint8Array(n); // 创建一个 Uint8Array 数组来存储解码后的字节数据
while (n--) {
ia[n] = bytes.charCodeAt(n); // 将每个字符的 ASCII 码转换为对应的字节值并存储到数组中
}
return new File([ia], fileName, { type: mime }); // 使用解码后的字节数据、文件名和 MIME 类型创建一个 File 对象并返回
}
},
destroyed: function() {
// 离开当前页面时,关闭摄像头
this.stopNavigator(); // 调用关闭摄像头的方法
}
}
</script>
<style>
.result_img {
width: 226px;
height: 195px;
background: #d8d8d8;
}
#bbb {
width: 500px;
text-align: center;
margin: auto;
}
</style>
(3)js文件
import request from '@/utils/request'
/**
* 人脸识别返回用户信息
* @param formData
* @returns {*}
*/
export function faceLogin(formData) {
return request({
url: '/auth/face/faceLogin',
method: 'post',
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
})
}
/**
*
*人脸注册
*/
export function registered(formData, id) {
return request({
url: '/auth/face/registerFace',
method: 'post',
data: formData,
params: {id},
headers: { //设置上传请求头
'Content-Type': 'multipart/form-data'
},
})
}
三、效果展示
我这里把电脑摄像头关了,就不做展示,但可以看到路径左边摄像头是开的。