All Products
Search
Document Center

Content Moderation:Image moderation

Last Updated:Jul 31, 2023

This topic describes how to use Content Moderation SDK for Java to moderate images for risky content.

Description

Content Moderation SDK for PHP supports both synchronous and asynchronous image moderation.

  • If you use synchronous image moderation, the moderation results are returned in real time. For more information about the related parameters, see /green/image/scan.

  • If you use asynchronous image moderation, you must poll the moderation results or configure a callback notification to receive the moderation results. For more information about the related parameters, see /green/image/asyncscan and /green/image/results.

Prerequisites

  • Java dependencies are installed. For more information, see Installation.

    Note

    You must use the Java version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.

  • The Extension.Uploader utility class is downloaded and imported into your project if you submit a local image or a binary image stream for image moderation.

(Recommended) Submit synchronous image moderation tasks

Operation

Description

Supported region

ImageSyncScanRequest

Sends synchronous requests to moderate images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

  • Submit the URL of an online image for image moderation

    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 {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation. 
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method. 
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported. 
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up. 
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content. 
             * In the scenes parameter, a value of porn indicates that the server detects pornography. 
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * Create a task for each image to be moderated. 
             * If you moderate multiple images in a request, the total response time that the server spends processing the request begins when the request is initiated and ends upon moderation of the last image. 
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time is extended. 
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a task for each image to be moderated. 
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Specify the image URL. The URL contains special characters and must be encoded. 
            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);
    
            /**
             * Specify the connection timeout period and read timeout period. The timeout period for the server to complete an image moderation request is 10s. 
             * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are returned after the server receives and processes your request. 
            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");
                // The moderation results of all images. 
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image. 
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                        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");
                                // Take further action based on the values of the scene and suggestion parameters. 
                                // Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • Submit the URL of a local image for image moderation

    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 {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation. 
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method. 
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported. 
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up. 
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content. 
             * In the scenes parameter, a value of porn indicates that the server detects pornography. 
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate a local image, use the following code snippet to generate a URL based on the storage path of the image. 
             * Then, submit the generated URL of the image to the server. 
             */
            String url = null;
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            try{
                url = clientUploader.uploadFile("d:/test.jpg");
            }catch (Exception e){
                e.printStackTrace();
            }
    
            /**
             * Create a task for each image to be moderated. 
             * If you moderate multiple images in a request, the total response time that the server spends processing the request begins when the request is initiated and ends upon moderation of the last image. 
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time is extended. 
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a task for each image to be moderated. 
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Set the url parameter to the image URL that is submitted to the server. The URL contains special characters and must be encoded. 
            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);
    
            /**
             * Specify the connection timeout period and read timeout period. The timeout period for the server to complete an image moderation request is 10s. 
             * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are returned after the server receives and processes your request. 
            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");
                // The moderation results of all images. 
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image. 
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                        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");
                                // Take further action based on the values of the scene and suggestion parameters. 
                                // Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • Submit a binary image stream for image moderation

    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 {
            /**
             * The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. To prevent security issues, we recommend that you use a RAM user to access API operations and perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation. 
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method. 
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported. 
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up. 
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content. 
             * In the scenes parameter, a value of porn indicates that the server detects pornography. 
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate a local image, use the following code snippet to generate a URL based on the storage path of the image. 
             * Then, submit the generated URL of the image to the server. 
             */
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            byte[] imageBytes = null;
            String url = null;
            try{
                // Read and convert a local image to binary data and submit the binary data for moderation. In the actual code, directly use the binary data of your image. 
                imageBytes = FileUtils.readFileToByteArray(new File("/Users/01fb4ab6420b5f34623e13b82b51ef87.jpg"));
                // Upload the binary stream to the server. 
                url = clientUploader.uploadBytes(imageBytes);
            }catch (Exception e){
                e.printStackTrace();
                throw e;
            }
    
            /**
             * Create a task for each image to be moderated. 
             * If you moderate multiple images in a request, the total response time that the server spends processing the request begins when the request is initiated and ends upon moderation of the last image. 
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time is extended. 
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a task for each image to be moderated. 
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Set the url parameter to the image URL that is submitted to the server. The URL contains special characters and must be encoded. 
            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);
    
            /**
             * Specify the connection timeout period and read timeout period. The timeout period for the server to complete an image moderation request is 10s. 
             * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are returned after the server receives and processes your request. 
            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");
                // The moderation results of all images. 
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image. 
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                        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");
                                // Take further action based on the values of the scene and suggestion parameters. 
                                // Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }

Submit asynchronous image moderation tasks

This section describes how to use Content Moderation SDK for Java to call the ImageAsyncScanRequest operation and moderate images for risky content. You can send an asynchronous request to submit image moderation tasks. When you submit the request, you can specify the callback URL to receive moderation results by setting the callback parameter. You can also call the ImageAsyncScanResultsRequest operation to poll the moderation results after Content Moderation processes the image moderation tasks.

Same as using synchronous image moderation, you can submit the URL of an online image, the URL of a local image, or a binary image stream for asynchronous image moderation. In this example, the URL of an online image is used.

Operation

Description

Supported region

ImageAsyncScanRequest

Sends asynchronous requests to moderate images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

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 {
        /**
         * The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. To prevent security issues, we recommend that you use a RAM user to access API operations and perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanRequest imageAsyncScanRequest = new ImageAsyncScanRequest();
        // Specify the response format of the operation. 
        imageAsyncScanRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method. 
        imageAsyncScanRequest.setMethod(MethodType.POST);
        imageAsyncScanRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported. 
        imageAsyncScanRequest.setProtocol(ProtocolType.HTTP);


        JSONObject httpBody = new JSONObject();
        /**
         * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
         * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up. 
         * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content. 
         * In the scenes parameter, a value of porn indicates that the server detects pornography. 
         */
        httpBody.put("scenes", Arrays.asList("porn"));
        httpBody.put("callback", "http://www.aliyundoc.com/xxx.json");
        httpBody.put("seed", "yourPersonalSeed");

        /**
         * Create a task for each image to be moderated. You can moderate a maximum of 50 images at a time. In this case, you must create 50 tasks. 
         * If you moderate multiple images in a request, the total response time that the server spends processing the request begins when the request is initiated and ends upon moderation of the last image. 
         * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time is extended. 
         * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a task for each image to be moderated. 
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());

        // Specify the image URL. The URL contains special characters and must be encoded. 
        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);

        /**
         * Specify the connection timeout period and read timeout period. The timeout period for the server to complete an image moderation request is 10s. 
         * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
         */
        imageAsyncScanRequest.setConnectTimeout(3000);
        imageAsyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageAsyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // The results that are returned after the server receives and processes your request. 
        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");
            // The moderation results of all images. 
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // The moderation result of a single image. 
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        // Save the task ID, which is used to poll the moderation results. 
                        System.out.println(((JSONObject)taskResult).getString("taskId"));
                    } else {
                        // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * The request failed to be processed. Analyze the failure based on the actual situation. 
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }
}

Query asynchronous image moderation results

Operation

Description

Supported region

ImageAsyncScanResultsRequest

Queries asynchronous image moderation results. You can query the moderation results of multiple asynchronous image moderation tasks at a time.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

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 {
        /**
         * The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. To prevent security issues, we recommend that you use a RAM user to access API operations and perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanResultsRequest imageAsyncScanResultsRequest = new ImageAsyncScanResultsRequest();
        // Specify the response format of the operation. 
        imageAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method. 
        imageAsyncScanResultsRequest.setMethod(MethodType.POST);
        imageAsyncScanResultsRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported. 
        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);

        /**
         // Specify the connection timeout period and read timeout period. 
         */
        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");
                                // Take further action based on the values of the scene and suggestion parameters. 
                                // Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                            }
                        }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();
        }
    }
}

Provide feedback on image moderation results

If the results of image moderation do not meet your expectations, you can call the ImageScanFeedbackRequest operation to modify the results. Content Moderation adds the moderated image to the similar image blacklist or whitelist based on your feedback. When you submit a similar image for moderation, Content Moderation returns moderation results based on the label in your feedback.

For more information, see /green/image/feedback.

Operation

Description

Supported region

ImageScanFeedbackRequest

Provides feedback on image moderation results and modifies the machine-assisted moderation results based on the feedback.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

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 {
        /**
         * The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. To prevent security issues, we recommend that you use a RAM user to access API operations and perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        ImageScanFeedbackRequest imageScanFeedbackRequest = new ImageScanFeedbackRequest();
        // Specify the response format of the operation. 
        imageScanFeedbackRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method. 
        imageScanFeedbackRequest.setMethod(MethodType.POST);
        imageScanFeedbackRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported. 
        imageScanFeedbackRequest.setProtocol(ProtocolType.HTTP);

        // scenes: the moderation scenarios. You can specify one or more moderation scenarios. 
        // suggestion: the moderation results that you expect to return. A value of pass indicates that the moderated image is normal. A value of block indicates that the moderated image contains violations. 
        JSONObject httpBody = new JSONObject();
        httpBody.put("suggestion", "block");
        httpBody.put("scenes", Arrays.asList("ad", "terrorism"));
        httpBody.put("url", "Image 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")) {
                    // The call is successful. 
                } 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();
        }
    }
}