spring-boot下百度云AI人脸检测配置

1、导入依赖



    com.baidu.aip
    java-sdk
    4.8.0

2、创建properties属性类,从配置文件获取配置信息

package com.vanzeSir.commons.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties("baidu.aip")
public class AipFaceProperties {
    private String appId;
    private String apiKey;
    private String secretKey;
}

3、从官网提取出来的工具类

package com.vanzeSir.commons.templates;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.vanzeSir.commons.properties.AipFaceProperties;
import org.json.JSONObject;

import java.util.HashMap;

public class AipFaceTemplate {

    private AipFaceProperties properties;

    public AipFaceTemplate(AipFaceProperties properties) {
        this.properties = properties;
    }

    /**
     * 根据上传的图片,校验是否包含人脸
     * @param body 图片字节数组
     * @return true 人脸; false 非人脸
     */
    public boolean detect(byte[] body) {

        AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());
        
        // 传入可选参数调用接口
        HashMap options = new HashMap();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");

        String imageType = "BASE64";

        String image = Base64Util.encode(body);

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);

        int code = res.getInt("error_code");

        return code == 0;
    }
}

4、创建配置类

package com.vanzeSir.commons.config;

import com.vanzeSir.commons.properties.AipFaceProperties;
import com.vanzeSir.commons.properties.OssProperties;
import com.vanzeSir.commons.properties.SmsProperties;
import com.vanzeSir.commons.templates.AipFaceTemplate;
import com.vanzeSir.commons.templates.OssTemplate;
import com.vanzeSir.commons.templates.SmsTemplate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
//自动的读取yml中配置信息,并赋值到SmsProperties、OssProperties对象中,将此对象存入容器
@EnableConfigurationProperties({
        SmsProperties.class,
        OssProperties.class,
        AipFaceProperties.class
})
public class TanhuaAutoConfiguration {

    @Bean
    public SmsTemplate smsTemplate(SmsProperties smsProperties) {
        SmsTemplate smsTemplate = new SmsTemplate(smsProperties);
        return smsTemplate;
    }

    @Bean
    public OssTemplate ossTemplate(OssProperties ossProperties) {
        return new OssTemplate(ossProperties);
    }

    @Bean
    public AipFaceTemplate aipFaceTemplate(AipFaceProperties properties) {
        return new AipFaceTemplate(properties);
    }
}

5、配置文件配置属性

baidu: 
 aip:
    appId: ********
    apiKey: ********************
    secretKey: *****************************

你可能感兴趣的:(spring)