Artificial Intelligence 12 min read

Implementing Face Registration and Login with Baidu Cloud AI: A Full‑Stack Demo

This tutorial walks through building a face‑registration and face‑login system using Baidu Cloud AI, covering requirement analysis, front‑end video capture, base64 image handling, back‑end Java Spring endpoints, and integration of the Baidu AipFace SDK to achieve secure biometric authentication.

Top Architect
Top Architect
Top Architect
Implementing Face Registration and Login with Baidu Cloud AI: A Full‑Stack Demo

In this article the author shares a complete demo for a face‑registration and face‑login feature, originally built for an intelligent airport project, and reproduces it as a stand‑alone example using Baidu Cloud AI services.

Requirement analysis

Face registration: capture a portrait via the browser video element, convert the image to a Base64 string, upload the image to the server, store the file path in the database, and add the face to Baidu Cloud's face library.

Face login: capture a portrait, send the Base64 data to the back‑end, compare it with the stored face using Baidu's SDK, and allow login when the similarity score exceeds 95%.

Front‑end implementation

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Baidu Cloud Face Registration</title>
    <style type="text/css">
        *{margin:0;padding:0;}
        html,body{width:100%;height:100%;}
        body{background:url(img/bg03.jpg) no-repeat center;}
        h1{color:#fff;text-align:center;line-height:80px;}
        .media{width:534px;height:400px;margin:40px auto 0;}
        #register{width:200px;height:50px;background:#2196f3;margin:60px auto 0;text-align:center;line-height:50px;color:#fff;border-radius:10px;}
        #canvas{display:none;}
        #shuru{width:200px;height:50px;background:#2196f3;margin:20px auto 0;}
    </style>
</head>
<body>
    <h1>百度云人脸注册</h1>
    <div id="shuru">用户名:<input type="text" name="username" id="username"/></div>
    <div class="media">
        <video id="video" width="450" height="300" autoplay></video>
        <canvas id="canvas" width="450" height="300"></canvas>
    </div>
    <button id="register">确定注册</button>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // Call camera and get video stream
        var video = document.getElementById('video');
        var userContext = canvas.getContext('2d');
        var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
        getUserMedia.call(navigator,{video:true,audio:false},function(localMediaStream){
            video.srcObject = localMediaStream;
        },function(e){
            console.log('获取摄像头失败!!');
        });
        // Register button click
        var btn = document.getElementById('register');
        btn.onclick = function(){
            var username = $('#username').val();
            if(username!=null){
                userContext.drawImage(video,0,0,450,300);
                var userImgSrc = document.getElementById('canvas').toDataURL('img/png');
                var faceBase = userImgSrc.split(',')[1];
                $.ajax({
                    url:"register",
                    type:"post",
                    data:{"faceBase":faceBase,"userName":username},
                    success:function(result){
                        if(result==='1'){
                            alert("注册成功!!,点击确认跳转至登录页面");
                            window.location.href="toLogin";
                        }else if(result==='2'){
                            alert("您已经注册过啦!!");
                        }else{
                            alert("系统错误!!");
                        }
                    }
                });
            }else{
                alert("用户名不能为空");
            }
        };
    </script>
</body>
</html>

Back‑end implementation (Java Spring)

private static final String APP_ID = "****";
private static final String API_KEY = "*******";
private static final String SECRET_KEY = "*******";

@Autowired
private IUserService userService;

@RequestMapping(value = "register", method = RequestMethod.POST)
public String register(String userName, String faceBase) throws IOException {
    if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(faceBase)) {
        // File upload path
        String upPath = ResourceUtils.getURL("classpath:").getPath() + "static\\photo";
        System.out.println(upPath);
        // Image file name
        String fileName = userName + System.currentTimeMillis() + ".png";
        System.out.println(upPath + "\\" + fileName);
        File file = new File(upPath + "\\" + fileName);
        // Initialize Baidu AipFace client
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // Insert user record into demo DB
        Users user = new Users();
        user.setUserName(userName);
        user.setUserPhoto(upPath + "\\" + fileName);
        Users exitUser = userService.selectUserByName(user);
        if (exitUser != null) {
            return "2"; // already exists
        }
        userService.addUsers(user);
        // Save captured image to server
        GenerateImage(faceBase, file);
        // Add face to Baidu face set
        facesetAddUser(client, faceBase, userName);
    }
    return "1"; // success
}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(String faceBase) {
    String faceData = faceBase;
    // Compare face data
    AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    Double num = verifyUser(faceData, client);
    if (num > 95) {
        return "1"; // login success
    } else {
        return "2"; // login failed
    }
}

/**
 * Face comparison
 */
public Double verifyUser(String imgBash64, AipFace client) {
    HashMap
options = new HashMap<>();
    JSONObject res = client.search(imgBash64, "BASE64", "user_01", options);
    System.out.println(res.toString(2));
    JSONObject user = (JSONObject) res.getJSONObject("result").getJSONArray("user_list").get(0);
    Double score = (Double) user.get("score");
    return score;
}

The article also includes screenshots of the UI, explanations of the three Baidu credentials (APP_ID, API_KEY, SECRET_KEY), and a discussion on the practicality of leveraging third‑party AI services rather than building the entire pipeline from scratch.

In conclusion, the demo demonstrates a straightforward way to integrate Baidu Cloud's face recognition API into a web application, covering both front‑end media capture and back‑end verification logic, and highlights the benefits of using existing cloud AI solutions for rapid development.

backendfrontendface recognitionDemobaidu-aiJava Spring
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.