Build a Face‑Recognition Demo with Baidu AI: Registration & Login

This article walks through creating a web‑based face‑recognition demo using Baidu Cloud AI, covering both front‑end video capture with HTML/JS and back‑end Java integration for user registration and login, complete with code snippets and key implementation steps.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Build a Face‑Recognition Demo with Baidu AI: Registration & Login

Introduction

Last year I worked on an intelligent airport project where facial boarding was a required feature. I only implemented the backend API that called the facial‑recognition device and returned data to the gate. Later I decided to create a demo that replicates this functionality using Baidu Cloud's face‑recognition service.

Requirements

1. Face Registration

step1: Capture a portrait using an HTML <video> element and JavaScript to access the laptop camera.

step2: Convert the captured image to a Base64 string and send it to the web backend.

step3: Store the username and the image path in the database.

step4: Upload the Base64 image to Baidu Cloud's face‑recognition server (offline private solutions are also possible).

2. Face Login

step1: Capture a portrait on the login page using the same HTML video component.

step2: Send the captured image data to the backend.

step3: Compare the captured image with the registered one by invoking Baidu Cloud's SDK; a similarity score above 95 permits login.

Implementation

Frontend page code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Baidu Cloud Face Registration</title>
    <style>
        *{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;color:#fff;line-height:50px;text-align:center;border-radius:10px;}
        #canvas{display:none;}
        #shuru{width:200px;height:50px;background:#2196f3;margin:20px auto;}
    </style>
</head>
<body>
    <h1>Baidu Cloud Face Registration</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 src="js/jquery-3.3.1.js"></script>
    <script>
        // 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(stream){
            video.srcObject = stream;
        },function(e){
            console.log('Failed to get camera');
        });
        // Register button click
        var btn = document.getElementById('register');
        btn.onclick = function(){
            var username = $('#username').val();
            if(username){
                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>

Backend Java code (Spring MVC controller):

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)) {
        String upPath = ResourceUtils.getURL("classpath:").getPath() + "static\\photo";
        String fileName = userName + System.currentTimeMillis() + ".png";
        File file = new File(upPath + "\\" + fileName);
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        Users user = new Users();
        user.setUserName(userName);
        user.setUserPhoto(upPath + "\\" + fileName);
        Users existUser = userService.selectUserByName(user);
        if(existUser != null) {
            return "2"; // already registered
        }
        userService.addUsers(user);
        GenerateImage(faceBase, file);
        facesetAddUser(client, faceBase, userName);
    }
    return "1"; // success
}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(String faceBase) {
    AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    Double score = verifyUser(faceBase, client);
    return score > 95 ? "1" : "2";
}

public Double verifyUser(String imgBash64, AipFace client) {
    HashMap<String, String> options = new HashMap<>();
    JSONObject res = client.search(imgBash64, "BASE64", "user_01", options);
    JSONObject user = (JSONObject) res.getJSONObject("result").getJSONArray("user_list").get(0);
    return (Double) user.get("score");
}

Key screenshots (illustrating registration page, login page, and success result) are shown below:

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendfrontendJavaface recognitionBaidu AIWeb demo
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

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.