文档

图片审核

更新时间:

本文介绍了如何使用Java SDK图片审核接口,检测图片中是否包含风险内容。

功能描述

图片审核支持同步检测和异步检测两种方式。

  • 同步检测实时返回检测结果。关于参数的详细信息,请参见同步检测

  • 异步检测需要您轮询结果或者通过callback回调通知获取检测结果。关于参数的详细信息,请参见异步检测

前提条件

  • 安装Java依赖。关于安装Java依赖的具体操作,请参见安装Java依赖

    说明

    请一定按照安装Java依赖页面中的版本安装,否则会导致调用失败。

  • 如果使用本地文件或者二进制文件检测,请下载并在项目工程中引入Extension.Uploader工具类

(推荐)提交图片同步检测任务

接口

描述

支持的地域

ImageSyncScanRequest

提交图片同步检测任务,对图片进行多个风险场景的识别,包括色情、暴恐涉政、广告、二维码、不良场景、Logo(商标台标)识别。

  • cn-shanghai:华东2(上海)

  • cn-beijing:华北2(北京)

  • cn-shenzhen:华南1(深圳)

  • ap-southeast-1:新加坡

示例代码

  • 传图片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.green.model.v20180509.ImageSyncScanRequest;
    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;
    
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
             * 常见获取环境变量方式:
             * 方式一:
             *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * 方式二:
             *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "建议从环境变量中获取RAM用户AccessKey ID",
                    "建议从环境变量中获取RAM用户AccessKey Secret");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // 指定API返回格式。
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // 指定请求方法。
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // 支持HTTP和HTTPS。
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
            JSONObject httpBody = new JSONObject();
            /**
             * 设置要检测的风险场景。计费依据此处传递的场景计算。
             * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
             * 例如,检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
             * porn:表示鉴黄场景。
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * 设置待检测图片。一张图片对应一个task。
             * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
             * 通常情况下批量检测的平均响应时间比单张检测的要长。一次批量提交的图片数越多,响应时间被拉长的概率越高。
             * 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task。
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // 设置图片链接。URL中有特殊字符,需要对URL进行encode编码。
            task.put("url", "http://www.aliyundoc.com/xxx.test.jpg");
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
             * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // 服务端接收到请求,完成处理后返回的结果。
            if (httpResponse != null && httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                // 每一张图片的检测结果。
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // 单张图片的处理结果。
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // 图片对应检测场景的处理结果。如果是多个场景,则会有每个场景的结果。
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // 根据scene和suggestion做相关处理。
                                // 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // 单张图片处理失败, 原因视具体的情况详细分析。
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * 表明请求整体处理失败,原因视具体的情况详细分析。
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • 传本地图片文件进行检测

    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.ImageSyncScanRequest;
    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;
    
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
             * 常见获取环境变量方式:
             * 方式一:
             *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * 方式二:
             *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "建议从环境变量中获取RAM用户AccessKey ID",
                    "建议从环境变量中获取RAM用户AccessKey Secret");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // 指定API返回格式。
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // 指定请求方法。
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // 支持HTTP和HTTPS。
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * 设置要检测的场景。计费依据此处传递的场景计算。
             * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
             * 例如:检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
             * porn:表示色情场景检测。
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * 如果您要检测的文件存于本地服务器上,可以通过下述代码片生成URL。
             * 再将返回的URL作为图片地址传递到服务端进行检测。
             */
            String url = null;
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            try{
                url = clientUploader.uploadFile("d:/test.jpg");
            }catch (Exception e){
                e.printStackTrace();
            }
    
            /**
             * 设置待检测图片。一张图片对应一个task。
             * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
             * 通常情况下批量检测的平均响应时间比单张检测的要长,一次批量提交的图片数越多,响应时间被拉长的概率越高。
             * 这里以单张图片检测作为示例。如果是批量图片检测,请自行构建多个task。
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // 设置图片链接为上传后的URL。URL中有特殊字符,需要对URL进行encode编码。
            task.put("url", url);
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
             * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // 服务端接收到请求,并完成处理后返回的结果。
            if (httpResponse != null && httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                // 每一张图片的检测结果。
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // 单张图片的处理结果。
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // 图片对应检测场景的处理结果。如果是多个场景,则会有每个场景的结果。
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // 根据scene和suggestion做相关处理。
                                // 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // 单张图片处理失败,原因视具体的情况详细分析。
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * 表明请求整体处理失败,原因视具体的情况详细分析。
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • 传图片二进制内容进行检测

    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.ImageSyncScanRequest;
    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;
    import org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
             * 常见获取环境变量方式:
             * 方式一:
             *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * 方式二:
             *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "建议从环境变量中获取RAM用户AccessKey ID",
                    "建议从环境变量中获取RAM用户AccessKey Secret");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // 指定API返回格式。
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // 指定请求方法。
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // 支持HTTP和HTTPS。
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * 设置要检测的场景。计费依据此处传递的场景计算。
             * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
             * 例如,检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
             * porn:表示色情场景检测。
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * 如果您要检测的文件存于本地服务器上,可以通过下述代码片生成URL。
             * 再将返回的URL作为图片地址传递到服务端进行检测。
             */
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            byte[] imageBytes = null;
            String url = null;
            try{
                // 这里读取本地文件作为二进制数据,当做输入做为示例。实际使用中请直接替换成您的图片二进制数据。
                imageBytes = FileUtils.readFileToByteArray(new File("/Users/01fb4ab6420b5f34623e13b82b51ef87.jpg"));
                // 上传到服务端。
                url = clientUploader.uploadBytes(imageBytes);
            }catch (Exception e){
                e.printStackTrace();
                throw e;
            }
    
            /**
             * 设置待检测图片。一张图片对应一个task。
             * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
             * 通常情况下批量检测的平均响应时间比单张检测的要长,一次批量提交的图片数越多,响应时间被拉长的概率越高。
             * 这里以单张图片检测作为示例。如果是批量图片检测,请自行构建多个task。
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // 设置图片链接为上传后的URL。URL中有特殊字符,需要对URL进行encode编码。
            task.put("url", url);
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
             * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // 服务端接收到请求,完成处理后返回的结果。
            if (httpResponse != null && httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                // 每一张图片的检测结果。
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // 单张图片的处理结果。
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // 图片对应检测场景的处理结果。如果是多个场景,则会有每个场景的结果。
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // 根据scene和suggestion做相关处理。
                                // 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // 单张图片处理失败,原因视具体的情况详细分析。
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * 表明请求整体处理失败,原因视具体的情况详细分析。
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }

提交图片异步检测任务

使用Java SDK对图片进行风险检测。通过异步请求提交检测任务,结果可以通过提交请求时设置callback,也可以通过ImageAsyncScanResultsRequest接口轮询。

异步检测支持的输入内容与同步检测一致(本地文件、图片URL、图片二进制流),以下仅以图片URL作为输入示例。

接口

描述

支持的地域

ImageAsyncScanRequest

提交图片异步检测任务,对图片进行多个风险场景的识别,包括色情、暴恐涉政、广告、二维码、不良场景、Logo(商标台标)识别。

  • cn-shanghai:华东2(上海)

  • cn-beijing:华北2(北京)

  • cn-shenzhen:华南1(深圳)

  • ap-southeast-1:新加坡

示例代码

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.model.v20180509.ImageAsyncScanRequest;
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;

import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

public class Main {

    public static void main(String[] args) throws Exception {
        /**
         * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
         * 常见获取环境变量方式:
         * 方式一:
         *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * 方式二:
         *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "建议从环境变量中获取RAM用户AccessKey ID",
                "建议从环境变量中获取RAM用户AccessKey Secret");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanRequest imageAsyncScanRequest = new ImageAsyncScanRequest();
        // 指定API返回格式。
        imageAsyncScanRequest.setAcceptFormat(FormatType.JSON);
        // 指定请求方法。
        imageAsyncScanRequest.setMethod(MethodType.POST);
        imageAsyncScanRequest.setEncoding("utf-8");
        // 支持HTTP和HTTPS。
        imageAsyncScanRequest.setProtocol(ProtocolType.HTTP);


        JSONObject httpBody = new JSONObject();
        /**
         * 设置要检测的场景。计费依据此处传递的场景计算。
         * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
         * 例如:检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
         * porn:表示色情场景检测。
         */
        httpBody.put("scenes", Arrays.asList("porn"));
        httpBody.put("callback", "http://www.aliyundoc.com/xxx.json");
        httpBody.put("seed", "yourPersonalSeed");

        /**
         * 设置待检测图片。一张图片对应一个task。最多支持50张图片同时检测,即需要构建50个task。
         * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
         * 通常情况下批量检测的平均响应时间比单张检测的要长,一次批量提交的图片数越多,响应时间被拉长的概率越高。
         * 这里以单张图片检测作为示例。如果是批量图片检测,请自行构建多个task。
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());

        // 设置图片链接。URL中有特殊字符,需要对URL进行encode编码。
        task.put("url", "http://www.aliyundoc.com/xxx.test.jpg");
        task.put("time", new Date());
        httpBody.put("tasks", Arrays.asList(task));

        imageAsyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
            "UTF-8", FormatType.JSON);

        /**
         * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
         * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
         */
        imageAsyncScanRequest.setConnectTimeout(3000);
        imageAsyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageAsyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 服务端接收到请求,完成处理后返回的结果。
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            System.out.println(JSON.toJSONString(scrResponse, true));
            int requestCode = scrResponse.getIntValue("code");
            // 每一张图片的检测结果。
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // 单张图片的处理结果。
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // 图片要检测的场景的处理结果,如果是多个场景,则会有每个场景的结果。
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        // 保存taskId用于轮询结果。
                        System.out.println(((JSONObject)taskResult).getString("taskId"));
                    } else {
                        // 单张图片处理失败,原因视具体的情况详细分析。
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * 表明请求整体处理失败,原因视具体的情况详细分析。
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }
}

查询图片异步检测结果

接口

描述

支持的地域

ImageAsyncScanResultsRequest

查询图片异步检测任务的结果。支持同时查询多个检测任务的返回结果。

  • cn-shanghai:华东2(上海)

  • cn-beijing:华北2(北京)

  • cn-shenzhen:华南1(深圳)

  • ap-southeast-1:新加坡

示例代码

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.ImageAsyncScanRequest;
import com.aliyuncs.green.model.v20180509.ImageAsyncScanResultsRequest;
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;

import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        /**
         * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
         * 常见获取环境变量方式:
         * 方式一:
         *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * 方式二:
         *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "建议从环境变量中获取RAM用户AccessKey ID",
                "建议从环境变量中获取RAM用户AccessKey Secret");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanResultsRequest imageAsyncScanResultsRequest = new ImageAsyncScanResultsRequest();
        // 指定API返回格式。
        imageAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);
        // 指定请求方法。
        imageAsyncScanResultsRequest.setMethod(MethodType.POST);
        imageAsyncScanResultsRequest.setEncoding("utf-8");
        // 支持HTTP和HTTPS。
        imageAsyncScanResultsRequest.setProtocol(ProtocolType.HTTP);


        List<String> taskIds = new ArrayList<String>();
        taskIds.add("img4hDosCHcrFk5jAMR80XWJN-1pZ@0p");
        imageAsyncScanResultsRequest.setHttpContent(JSON.toJSONString(taskIds).getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请务必设置超时时间。
         */
        imageAsyncScanResultsRequest.setConnectTimeout(3000);
        imageAsyncScanResultsRequest.setReadTimeout(6000);

        try {
            HttpResponse httpResponse = client.doAction(imageAsyncScanResultsRequest);

            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if(200 == ((JSONObject)taskResult).getInteger("code")){
                            JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject)sceneResult).getString("scene");
                                String suggestion = ((JSONObject)sceneResult).getString("suggestion");
                                // 根据scene和suggestion做相关的处理。
                                // 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
                            }
                        }else{
                            System.out.println("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

图片检测结果反馈

如果您认为图片检测结果与您的预期不符,可以通过图片检测结果反馈接口,对检测结果进行纠正(系统会根据您反馈的结果,将图片添加到相似图片的黑名单库或者白名单库)。当您再次提交相似的内容进行检测时,以您反馈的label返回结果。

关于接口的说明,请参见检测结果反馈

接口

描述

支持的Region

ImageScanFeedbackRequest

提交图片检测结果的反馈,以人工反馈的检测结果纠正算法检测结果。

  • cn-shanghai:华东2(上海)

  • cn-beijing:华北2(北京)

  • cn-shenzhen:华南1(深圳)

  • ap-southeast-1:新加坡

示例代码

import com.alibaba.fastjson.JSON;
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.ImageScanFeedbackRequest;
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;

import java.util.Arrays;


public class Main {

    public static void main(String[] args) throws Exception {
        /**
         * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。 
         * 常见获取环境变量方式:
         * 方式一:
         *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * 方式二:
         *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "建议从环境变量中获取RAM用户AccessKey ID",
                "建议从环境变量中获取RAM用户AccessKey Secret");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
        IAcsClient client = new DefaultAcsClient(profile);

        ImageScanFeedbackRequest imageScanFeedbackRequest = new ImageScanFeedbackRequest();
        // 指定API返回格式。
        imageScanFeedbackRequest.setAcceptFormat(FormatType.JSON);
        // 指定请求方法。
        imageScanFeedbackRequest.setMethod(MethodType.POST);
        imageScanFeedbackRequest.setEncoding("utf-8");
        // 支持HTTP和HTTPS。
        imageScanFeedbackRequest.setProtocol(ProtocolType.HTTP);

        // scenes:检测场景,支持指定多个场景。
        // suggestion:期望的检测结果。pass:正常;block:违规。
        JSONObject httpBody = new JSONObject();
        httpBody.put("suggestion", "block");
        httpBody.put("scenes", Arrays.asList("ad", "terrorism"));
        httpBody.put("url", "图片链接");

        imageScanFeedbackRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);

        imageScanFeedbackRequest.setConnectTimeout(3000);
        imageScanFeedbackRequest.setReadTimeout(10000);
        try {
            HttpResponse httpResponse = client.doAction(imageScanFeedbackRequest);
            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    // 调用成功。
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

  • 本页导读 (0)
文档反馈