This topic describes how to use Alibaba Cloud Image Search SDKs for Java.

API operations

Operation Description
Add Adds images.
SearchImageByPic Searches for similar images based on a new image.
SearchImageByName Searches for similar images based on the name of an existing image in the image gallery.
Delete Deletes images.

Preparations

  • Before you install and use Alibaba Cloud SDKs, make sure that you have created an Alibaba Cloud account and obtained an AccessKey pair. For more information, see Obtain an AccessKey pair.
  • Add the Alibaba Cloud Image Search SDK for Java to your project by performing the following operations:
    Import the Alibaba Cloud Image Search SDK for Java as a Maven dependency, and add the SDK to your project.
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-imagesearch</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>[4.3.2,5.0.0)</version>
    </dependency>
    You can import the following libraries based on your business needs:
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

Create a client

  1. Specify an endpoint to access your Image Search instance. In this example, the Image Search instance resides in the China (Shanghai) region.
    DefaultProfile.addEndpoint( "<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com");
    Note For more information about endpoints, see Request syntax.
  2. Create a profile object. Create a profile object for IClientProfile. This object contains information about the AccessKey ID, the AccessKey secret, and the region.
    IClientProfile profile = DefaultProfile.getProfile("<region>", "<your-access-key-id>", "<your-access-key-secret>");
  3. Create the client. Create an IAcsClient object named client from the IClientProfile class. Subsequent responses are retrieved from IAcsClient.
    IAcsClient client = new DefaultAcsClient(profile);

Add images

The following sample code is used to add images:
AddImageRequest request = new AddImageRequest();
    // Required. The name of the Image Search instance.
    request.setInstanceName("demo");
    // Required. The product ID, which can be up to 512 characters in length.
    // A product ID can correspond to multiple image names.
    request.setProductId("test");
    // Required. The image name, which can be up to 512 characters in length.
    // 1. An image is uniquely identified by the values of the ProductId and PicName parameters.
    // 2. If you add images that have the same ProductId and PicName for multiple times, the image that is added in the last operation overwrites the images that are added in previous operations.
    request.setPicName("test");
    // Optional. The category of the image.
    // 1. For product image searches, if you specify a category for an image, the specified category prevails. If you do not specify a category for an image, the system predicts the category, and returns the prediction result in the response.
    // 2. For generic image searches, the system sets the category ID to 88888888, regardless of whether you specify a category for an image.
    request.setCategoryId(1);
    byte[] bytes2 = getBytes("/home/admin/demo.jpg");
    Base64 base64 = new Base64();
    String encodePicContent = base64.encodeToString(bytes2);
    // Required. The image file that is encoded in Base64.
    // The file size of the image cannot exceed 2 MB. The transmission time-out period cannot exceed 5 seconds. Only JPG and PNG images are supported.
    // For product, and generic image searches, the length and the width of the image must range from 200 pixels to 1,024 pixels.
    // The image cannot contain rotation information.
    request.setPicContent(encodePicContent);

    // Optional. Specifies whether to recognize the subject in the image and search for images based on the recognized subject. The default value is true.
    // 1. true: The system recognizes the subject in the image, and searches for images based on the recognized subject. You can obtain the recognition result in the response.
    // 2. false: The system does not recognize the subject of the image, and searches for images based on the entire image.
    request.setCrop(true);
    // Optional. The subject area in the image. The subject area is in the format of x1,x2,y1,y2. x1 and y1 represent the upper-left corner pixel. x2 and y2 represent the lower-right pixel.
    // If you specify the Region parameter, the system searches for images based on this parameter setting regardless of the value of the Crop parameter.
    request.setRegion("280,486,232,351");

    // Optional. The integer attribute. The attribute can be used to filter images when you search for images. If you specify this parameter, the response includes this parameter and its value.
    // For example, you can set different IntAttr values for images of different sites or images of different users. This narrows down the search scope when you specify the integer attribute to search for images.
    request.setIntAttr(0);
    // Optional. The string attribute. The value can be up to 128 characters in length. The attribute can be used to filter images when you search for images. If you specify this parameter, the response includes this parameter and its value.
    request.setStrAttr("demo");
    // Optional. The user-defined content. The value can be up to 4,096 characters in length.
    // If you specify this parameter, the response includes this parameter and its value. You can add text, such as an image description.
    request.setCustomContent("1");

    try {
        AddImageResponse response = client.getAcsResponse(request)
    } catch (ClientException e) {
        // An exception is thrown due to an invalid parameter, an unavailable instance, or other reasons.
        e.printStackTrace();
    }

Search for images

  • Search for similar images based on a new image.
    SearchImageRequest request = new SearchImageRequest();
        // Required. The name of the Image Search instance.
        request.setInstanceName("demo");
        // Optional. The search type. Valid values:
        // 1. SearchByPic: The system searches for similar images based on a new image. This value is the default value.
        // 2. SearchByName: The system searches for similar images based on the name of an existing image.
        // request.setType("SearchByPic");
    
        byte[] bytes2 = getBytes("/home/admin/demo.jpg");
        Base64 base64 = new Base64();
        String encodePicContent = base64.encodeToString(bytes2);
        // The image file that is encoded in Base64. The file size of the image cannot exceed 2 MB. The transmission time-out period cannot exceed 5 seconds. Only JPG and PNG images are supported.
        // For product, and generic image searches, the length and the width of the image must range from 200 pixels to 1,024 pixels.
        // The image cannot contain rotation information.
        // 1. If the Type parameter is set to SearchByPic, this parameter is required.
        // 2. If the Type parameter is set to SearchByName, this parameter is not required.
        request.setPicContent(encodePicContent);
    
        // Optional. The category of the image.
        // 1. For product image searches, if you specify a category for an image, the specified category prevails. If you do not specify a category for an image, the system predicts the category, and returns the prediction result in the response.
        // 2. For generic image searches, the system sets the category ID to 88888888, regardless of whether you specify a category for an image.
        request.setCategoryId(1);
    
        // Optional. Specifies whether to recognize the subject in the image and search for images based on the recognized subject. The default value is true.
        // 1. true: The system recognizes the subject in the image, and searches for images based on the recognized subject. You can obtain the recognition result in the response.
        // 2. false: The system does not recognize the subject of the image, and searches for images based on the entire image.
    
        // Optional. The subject area in the image. The subject area is in the format of x1,x2,y1,y2. x1 and y1 represent the upper-left corner pixel. x2 and y2 represent the lower-right pixel.
        // If you specify the Region parameter, the system searches for images based on this parameter setting regardless of the value of the Crop parameter.
        request.setRegion("280,486,232,351");
    
        // Optional. The number of images to be returned. Valid values: 1 to 100. Default value: 10.
        request.setNum(2);
        // Optional. No. of the first image to be displayed. Valid values: 0 to 499. Default value: 0.
        request.setStart(1);
    
        // Optional. The filter condition.
        // The int_attr field supports the following operators: >, >=, <=, and =. The str_attr field supports the following operators: = and !=. Multiple filter conditions are joined by AND or OR.
        // Examples:
        //  1. Filter results based on IntAttr: int_attr>=100
        //  2. Filter results based on StrAttr: str_attr!="value1"
        //  3. Filter results based on IntAttr and StrAttr: int_attr=1000 AND str_attr="value1"
        request.setFilter("int_attr=1");
    
        try {
            SearchImageResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
  • Search for similar images based on an existing image that is identified by the ProductId and PicName parameters.
    SearchImageRequest request = new SearchImageRequest();
        // Required. The name of the Image Search instance.
        request.setInstanceName("demo");
    
        // Optional. The search type. Valid values:
        // 1. SearchByPic: The system searches for similar images based on a new image. This value is the default value.
        // 2. SearchByName: The system searches for similar images based on the name of an existing image.
         request.setType("SearchByName");
    
        // The ID of the product.
        // 1. If the Type parameter is set to SearchByPic, this parameter is not required.
        // 2. If the Type parameter is set to SearchByName, the product ID of the existing image is required.
        request.setProductId("test");
    
        // The name of the image.
        // 1. If the Type parameter is set to SearchByPic, this parameter is not required.
        // 2. If the Type parameter is set to SearchByName, the name of the existing image is required.
        request.setPicName("test");
    
        // Optional. The category of the image.
        // 1. For product image searches, if you specify a category for an image, the specified category prevails. If you do not specify a category for an image, the system predicts the category, and returns the prediction result in the response.
        // 2. For generic image searches, the system sets the category ID to 88888888, regardless of whether you specify a category for an image.
        request.setCategoryId(1);
    
        // Optional. Specifies whether to recognize the subject in the image and search for images based on the recognized subject. The default value is true.
        // 1. true: The system recognizes the subject in the image, and searches for images based on the recognized subject. You can obtain the recognition result in the response.
        // 2. false: The system does not recognize the subject of the image, and searches for images based on the entire image.
        request.setCrop(false);
        // Optional. The subject area in the image. The subject area is in the format of x1,x2,y1,y2. x1 and y1 represent the upper-left corner pixel. x2 and y2 represent the lower-right pixel.
        // If you specify the Region parameter, the system searches for images based on this parameter setting regardless of the value of the Crop parameter.
        request.setRegion("280,486,232,351");
    
        // Optional. The number of images to be returned. Valid values: 1 to 100. Default value: 10.
        request.setNum(2);
        // Optional. No. of the first image to be displayed. Valid values: 0 to 499. Default value: 0.
        request.setStart(1);
    
        // Optional. The filter condition.
        // The int_attr field supports the following operators: >, >=, <=, and =. The str_attr field supports the following operators: = and !=. Multiple filter conditions are joined by AND or OR.
        // Examples:
        //  1. Filter results based on IntAttr: int_attr>=100
        //  2. Filter results based on StrAttr: str_attr!="value1"
        //  3. Filter results based on IntAttr and StrAttr: int_attr=1000 AND str_attr="value1"
        request.setFilter("int_attr=1");
    
        try {
            SearchImageResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

Delete images

The following sample code is used to delete images:
DeleteImageRequest request = new DeleteImageRequest();
    // Required. The name of the Image Search instance.
    request.setInstanceName("demo");

    // Required. The product ID.
    request.setProductId("test");

    // Optional. The image name. If this parameter is not specified, the system deletes all the images that correspond to the specified ProductId parameter. If this parameter is specified, the system deletes only the image that is specified by the ProductId and PicName parameters.
    request.setPicName("test");

    try {
        DeleteImageResponse response = client.getAcsResponse(request);
    } catch (ClientException e) {
        e.printStackTrace();
    }

Additional information

The following sample code is used to obtain the binary array of the image:
private static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            // picture max size is 2MB
            ByteArrayOutputStream bos = new ByteArrayOutputStream(2000 * 1024);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

Download the SDK demo

Download the demo of the Alibaba Cloud Image Search SDK for Java.