This topic shows you how to use Image Search SDK for Java and provides sample code.

Methods

Method 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.

SDK demo

Download the demo of Image Search SDK for Java.

Before you begin

  • Before you install and use Alibaba Cloud SDK, make sure that you have created an Alibaba Cloud account and obtained an AccessKey pair. For more information, see Create an AccessKey pair.
  • Add Image Search SDK for Java to your project
    Import Image Search SDK for Java as a Maven dependency, and add the SDK to your project.
      <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>imagesearch20201214</artifactId>
            <version>3.1.1</version>
       </dependency>

Add

  • Sample code
    import com.aliyun.imagesearch20201214.Client;
    import com.aliyun.imagesearch20201214.models.AddImageAdvanceRequest;
    import com.aliyun.imagesearch20201214.models.AddImageResponse;
    import com.aliyun.imagesearch20201214.models.Config;
    import com.aliyun.tea.TeaException;
    import com.aliyun.teautil.models.RuntimeOptions;
    import java.io.FileInputStream;
    import java.io.InputStream;
    public class Add {
        public static void main(String[] args) throws Exception {
            Config authConfig = new Config();
            authConfig.accessKeyId = "XXXXXX";
            authConfig.accessKeySecret = "XXXXXXXXX";
            authConfig.type = "access_key";
            authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
            authConfig.regionId = "cn-shanghai";
            Client client = new Client(authConfig);
            AddImageAdvanceRequest request = new AddImageAdvanceRequest();
            // Required. The name of the Image Search instance.
            request.instanceName = "XXXXXXXXXXX";
             // Required. The product ID, which can be up to 512 characters in length.
             // A product ID can correspond to multiple image names.
            request.productId = "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 values for multiple times, the image that is added in the last operation overwrites the images that are added in previous operations.
            request.picName = "1000";
            // Optional. The image category.
            // 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 parameter value is set to 88888888 regardless of whether a category is set.
            request.categoryId = 3;
             // 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 texts, such as an image description.
            request.customContent = "this is a simple test";
             // 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 from different sites or different users. This narrows down the search scope when you specify the integer attribute to search for images.
            request.intAttr = 56;
            // 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.strAttr = "test";
            // 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. If this parameter is set to 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. If this parameter is set to false, the system does not recognize the subject of the image, and searches for images based on the entire image.
            request.crop = 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 corner 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.region = "167,467,221,407";
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            String picName = "D:/123.jpg";
            InputStream inputStream = new FileInputStream(picName);
            // The image file. The file size of the image cannot exceed 2 MB. The transmission timeout 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.picContentObject = inputStream;
            try {
                AddImageResponse response = client.addImageAdvance(request,runtimeOptions);
               System.out.println("success: " + response.getBody().success + ". message: " 
                    + response.getBody().message        
                    + ". categoryId: " + response.getBody().picInfo.categoryId 
                    + ". region:" + response.getBody().picInfo.region        
                    + ". requestId: " + response.getBody().requestId);
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • Sample responses
    success: true. message: success. categoryId: 9. region:383,681,291,549. requestId: 016D63E3-D0C5-42D3-8879-55E1A705FBA4

SearchImageByPic

  • Sample code
    import com.aliyun.imagesearch20201214.Client;
    import com.aliyun.imagesearch20201214.models.Config;
    import com.aliyun.imagesearch20201214.models.SearchImageByPicAdvanceRequest;
    import com.aliyun.imagesearch20201214.models.SearchImageByPicResponse;
    import com.aliyun.tea.TeaException;
    import com.aliyun.teautil.models.RuntimeOptions;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.util.List;
    public class SearchImageByPic {
        public static void main(String[] args) throws Exception {
            Config authConfig = new Config();
            authConfig.accessKeyId = "XXXXXXXX";
            authConfig.accessKeySecret = "XXXXXXXXXX";
            authConfig.type = "access_key";
            authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
            authConfig.regionId = "cn-shanghai";
            Client client = new Client(authConfig);
            SearchImageByPicAdvanceRequest request = new SearchImageByPicAdvanceRequest();
            // Required. The name of the Image Search instance.
            request.instanceName = "XXXXXXXXX";
            // Optional. The product category.
            // 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 parameter value is set to 88888888 regardless of whether a category is set.
            request.categoryId = 3;
            // Optional. The number of images to be returned. Valid values: 1 to 100. Default value: 10.
            request.num = 10;
             // Optional. No. of the first image to be displayed. Valid values: 0 to 499. Default value: 0.
            request.start = 0;
              // 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. If this parameter is set to 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. If this parameter is set to false, the system does not recognize the subject of the image, and searches for images based on the entire image.
            request.crop = 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 corner 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.region="167,467,221,407";
            // 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.filter="int_attr=56 AND str_attr=\"test\"";
            InputStream inputStream = new FileInputStream("D:/123.jpg");
             // The image file. The file size of the image cannot exceed 2 MB. The transmission timeout 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.picContentObject = inputStream;
            request.num = 10;
            request.start = 0;
            RuntimeOptions runtimeObject =  new RuntimeOptions();
            try {
                SearchImageByPicResponse response = client.searchImageByPicAdvance(request, runtimeObject);
                System.out.println(response.getBody().requestId);
                System.out.println(response.getBody().picInfo.categoryId);
                System.out.println(response.getBody().picInfo.region);
                List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> auctions = response.getBody().getAuctions();
                for(SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions auction:auctions) {    
                    System.out.println(auction.categoryId + " " + auction.picName + " " 
                        + auction.productId + " " + auction.customContent + " " + auction.score + " " 
                        + auction.strAttr + " " + auction.intAttr);
                }
                System.out.println("Multi-subject information");
                SearchImageByPicResponseBody.SearchImageByPicResponseBodyPicInfo picInfo = response.getBody().getPicInfo();
                for (SearchImageByPicResponseBody.SearchImageByPicResponseBodyPicInfoMultiRegion multiRegion : picInfo.getMultiRegion()) {    
                    System.out.println(multiRegion.region);
                }
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • Sample responses
    09BE019A-AE3D-4D22-99C9-10533D8AC631
    3
    167,467,221,407
    3 1000 test this is a simple test 1.0 test 56
    Multi-subject information
    112,440,76,387

SearchImageByName

  • Sample code
    import com.aliyun.imagesearch20201214.Client;
    import com.aliyun.imagesearch20201214.models.Config;
    import com.aliyun.imagesearch20201214.models.SearchImageByNameRequest;
    import com.aliyun.imagesearch20201214.models.SearchImageByNameResponse;
    import com.aliyun.tea.TeaException;
    import com.aliyun.teautil.models.RuntimeOptions;
    import java.util.List;
    public class  SearchImageByName{
        public static void main(String[] args) throws Exception {
            // The configurations.
            Config authConfig = new Config();
            authConfig.accessKeyId = "XXXXXX";
            authConfig.accessKeySecret = "XXXXXXXXX";
            authConfig.type = "access_key";
            authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
            authConfig.regionId = "cn-shanghai";
            Client client = new Client(authConfig);
            SearchImageByNameRequest request = new SearchImageByNameRequest();
            // Required. The name of the Image Search instance.
            request.instanceName = "XXXXXXXXX";
             // Required. The product ID, which can be up to 512 characters in length.
            // A product ID can correspond to multiple image names.
            request.productId = "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.
            request.picName = "1000";
             // Optional. The product category.
            // 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 parameter value is set to 88888888 regardless of whether a category is set.
            request.categoryId = 3;
            // Optional. The number of images to be returned. Valid values: 1 to 100. Default value: 10.
            request.num =10;
             // Optional. No. of the first image to be displayed. Valid values: 0 to 499. Default value: 0.
            request.start =0;
            // 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.filter = "int_attr=56 AND str_attr =\"test\"";
            RuntimeOptions runtimeObject =  new RuntimeOptions();
            try {
                SearchImageByNameResponse response = client.searchImageByName(request, runtimeObject);
                System.out.println(response.getBody().requestId);
                System.out.println(response.getBody().picInfo.categoryId);
                System.out.println(response.getBody().picInfo.region);
                List<SearchImageByNameResponseBody.SearchImageByNameResponseBodyAuctions> auctions = response.getBody().getAuctions();
                for(SearchImageByNameResponseBody.SearchImageByNameResponseBodyAuctions auction:auctions) {    
                    System.out.println(auction.categoryId + " " + auction.picName + " " 
                        + auction.productId + " " + auction.customContent + " " + auction.score + " " 
                        + auction.strAttr + " " + auction.intAttr);
                }
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • Sample responses
    8F2441C8-EA05-461B-A4AC-5F5DE25FAC21
    3
    null
    3 1000 test this is a simple test 1.0 test 56
                        

Delete

  • Sample code
    import com.aliyun.imagesearch20201214.Client;
    import com.aliyun.imagesearch20201214.models.Config;
    import com.aliyun.imagesearch20201214.models.DeleteImageRequest;
    import com.aliyun.imagesearch20201214.models.DeleteImageResponse;
    import com.aliyun.tea.TeaException;
    import com.aliyun.teautil.models.RuntimeOptions;
    public class Delete {
        public static void main(String[] args) throws Exception {
            Config authConfig = new Config();
            authConfig.accessKeyId = "XXXXXXXX";
            authConfig.accessKeySecret = "XXXXXXXXXX";
            authConfig.type = "access_key";
            authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
            authConfig.regionId = "cn-shanghai";
            Client client = new Client(authConfig);
            DeleteImageRequest request = new DeleteImageRequest();
            // Required. The name of the Image Search instance.
            request.instanceName = "XXXXXXXXXXXX";
            // Required. The product ID, which can be up to 512 characters in length.
            // A product ID can correspond to multiple image names.
            request.productId = "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.picName = "1000";
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            try {
                DeleteImageResponse response = client.deleteImage(request, runtimeOptions);
                System.out.println("requestId: " + response.requestId + ". success: " + response.success + ". message: " + response.message);
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • Sample responses
    requestId: 927AE217-90E1-4B48-9413-7508FCB4CE51. success: true. message: success