1. 程式人生 > 其它 >呼叫阿里雲API實現人臉登入

呼叫阿里雲API實現人臉登入

步驟

一. 首先判斷前端引數是否傳入正確

和之前一樣 若引數不合法則將異常丟擲

public class FaceLoginBO {
    @NotBlank
    private String img64;
    @NotBlank
    private String username;

    public String getImg64() {
        return img64;
    }

    public void setImg64(String img64) {
        this.img64 = img64;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
        if (bindingResult.hasErrors()) {
            Map<String, String> bindResultErrors = super.getBindResultErrors(bindingResult);

            GraceJSONResult.errorMap(bindResultErrors);
        }

二. 根據faceId將Mongdo的圖片查詢到並轉換為Base64 若無法找到圖片則表示建立Admin帳號時未傳入人臉圖片 直接丟擲異常即可

業務邏輯:

  1. 根據username將使用者資訊從資料庫中查出 並將faceId取出
    直接呼叫service就可以了 沒有什麼好說的
        AdminUser adminUser = adminService.findUsernameByAdmin(faceLoginBO.getUsername());
        String faceId = adminUser.getFaceId();

        if (StringUtils.isBlank(faceId)) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }
  1. 使用restTemplate遠端呼叫根據faceid取出圖片並將圖片轉換為base64
    呼叫之前的方法獲取到file物件 然後直接呼叫utils將檔案轉換為base64
    public GraceJSONResult getFileBase64ByFaceId(String faceId) {
        if (StringUtils.isBlank(faceId)) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }

        File faceFile = downloadFaceFile(faceId);

        String fileToBase64 = FileUtils.fileToBase64(faceFile);

        return GraceJSONResult.ok(fileToBase64);
    }

utils邏輯很簡單
先將檔案轉換為自己陣列 然後根據位元組陣列呼叫java工具類即可

    public static String fileToBase64(File file) {//將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
        InputStream in = null;
        byte[] fileData = null;
        // 讀取檔案位元組陣列
        try {
            in = new FileInputStream(file);
            fileData = new byte[in.available()];
            in.read(fileData);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Base64.Encoder encoder = Base64.getEncoder();

        return encoder.encodeToString(fileData);
    }

因為要遠端呼叫 所以要使用restTemplate 例項化一個restTemplate bean

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

直接遠端呼叫即可

        String getFileBase64Url = "http://www.imoocnews.com:8004/fs/getFileBase64ByFaceId?faceId=" + faceId;
        GraceJSONResult base64Result = restTemplate.getForObject(getFileBase64Url, GraceJSONResult.class);

        if (base64Result == null) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }

        // faceA 資料庫中的圖片
        String faceBase64A = (String) base64Result.getData();
        if (faceBase64A == null) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }

三. 呼叫阿里雲面部識別API 將前端傳入的圖片base64與資料庫中的圖片base64傳遞給面部失敗api中 若可信度大於70則登入成功

四.. 若登入成功則設定cookie