本文提供了使用Java SDK对给定的人脸图片进行属性检测的示例代码。人脸属性检测仅支持以图片作为检测媒介。

说明 具体参数说明请参见人脸属性检测API接口描述

准备工作

在进行具体的服务调用之前,请参考以下步骤,完成准备工作:
  1. 创建阿里云AccessKeyId和AccessKeySecret。具体请参考创建AccessKey
  2. 安装Java依赖。具体请参考安装Java依赖
  3. 下载并在项目工程中引入Extension.Uploader工具类

传入URL示例代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.DetectFaceRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 人脸属性检测代码示例
 */
public class DetectFaceSample {

    public static void main(String[] args) throws Exception {
        //请替换成您自己的accessKeyId、accessKeySecret
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "您的accessKeyId", "您的accessKeySecret");
        DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        DetectFaceRequest detectFaceRequest = new DetectFaceRequest();
        detectFaceRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        detectFaceRequest.setMethod(MethodType.POST); // 指定请求方法
        detectFaceRequest.setEncoding("utf-8");
        detectFaceRequest.setHttpContentType(FormatType.JSON);

        JSONObject data = new JSONObject();
        // 设置待检测的人脸图片
        data.put("url", "http://xxxx.xx/xx");
        detectFaceRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
         * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常
         */
        detectFaceRequest.setConnectTimeout(3000);
        detectFaceRequest.setReadTimeout(10000);

        HttpResponse httpResponse;
        try {
            httpResponse = client.doAction(detectFaceRequest);
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return;
        }

        // 判断HTTP请求是否成功
        if (httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
            if (200 == scrResponse.getInteger("code")) {
                JSONObject result = scrResponse.getJSONObject("data");
                if (200 == result.getInteger("code")) {
                    /**
                     *   结果数据
                     */
                    JSONArray faces = result.getJSONArray("faces");
                    // 检测到的人脸个数
                    System.out.println("faceCount:" + faces.size());
                    // 每个人脸的结果详情
                    for (int i = 0; i < faces.size(); i++) {
                        System.out.println("face" + i + ": " + faces.getJSONObject(i).toJSONString());
                    }
                } else {
                    System.out.println("result fail: " + result.toJSONString());
                }
            } else {
                /**
                 * 请求整体处理失败,原因视具体的情况详细分析
                 */
                System.out.println("request fail:" + scrResponse.toJSONString());
            }
        } else {
            /**
             * HTTP请求失败,错误详情
             */
            System.out.println("response fail!" +
                    "\ncode:" + httpResponse.getStatus() +
                    "\nmsg:" + new String(httpResponse.getHttpContent(), "UTF-8"));
        }

    }
}

传入本地文件示例代码

说明 内容安全提供上传SDK,帮助您上传本地文件。若有使用需求,请通过工单提申请。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.extension.uploader.ClientUploader;
import com.aliyuncs.green.model.v20180509.DetectFaceRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 人脸属性检测:本地图片文件检测样例
 */
public class DetectFaceFileSample {

    public static void main(String[] args) throws Exception {
        //请替换成你自己的accessKeyId、accessKeySecret
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "您的accessKeyId", "您的accessKeySecret");
        DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        DetectFaceRequest detectFaceRequest = new DetectFaceRequest();
        detectFaceRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        detectFaceRequest.setMethod(MethodType.POST); // 指定请求方法
        detectFaceRequest.setEncoding("utf-8");
        detectFaceRequest.setHttpContentType(FormatType.JSON);

        ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);

        String url1 = null;
        try{
            //上传待检测人脸图片
            url1 = clientUploader.uploadFile("d:/image1.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }

        JSONObject data = new JSONObject();
        // 设置待检测的人脸图片
        data.put("url", url1);
        detectFaceRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
         * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常
         */
        detectFaceRequest.setConnectTimeout(3000);
        detectFaceRequest.setReadTimeout(10000);

        HttpResponse httpResponse;
        try {
            httpResponse = client.doAction(detectFaceRequest);
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return;
        }

        // 判断HTTP请求是否成功
        if (httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
            if (200 == scrResponse.getInteger("code")) {
                JSONObject result = scrResponse.getJSONObject("data");
                if (200 == result.getInteger("code")) {
                    /**
                     *   结果数据
                     */
                    JSONArray faces = result.getJSONArray("faces");
                    // 检测到的人脸个数
                    System.out.println("faceCount:" + faces.size());
                    // 每个人脸的结果详情
                    for (int i = 0; i < faces.size(); i++) {
                        System.out.println("face" + i + ": " + faces.getJSONObject(i).toJSONString());
                    }
                } else {
                    System.out.println("result fail: " + result.toJSONString());
                }
            } else {
                /**
                 * 请求整体处理失败,原因视具体的情况详细分析
                 */
                System.out.println("request fail:" + scrResponse.toJSONString());
            }
        } else {
            /**
             * HTTP 请求失败,错误详情
             */
            System.out.println("response fail!" +
                    "\ncode:" + httpResponse.getStatus() +
                    "\nmsg:" + new String(httpResponse.getHttpContent(), "UTF-8"));
        }

    }
}