All Products
Search
Document Center

Java SDK

Last Updated: Jul 01, 2019

Preparations

  1. Before installing and using Alibaba Cloud SDKs, make sure that you have registered an Alibaba Cloud account and generated an AccessKey. For more information, see Create an AccessKey.

  2. Add the SDK to the project.
    Import the Image Search library as a Maven dependency.

    1. <dependency>
    2. <groupId>com.aliyun</groupId>
    3. <artifactId>aliyun-java-sdk-imagesearch</artifactId>
    4. <version>2.0.0</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>com.aliyun</groupId>
    8. <artifactId>aliyun-java-sdk-core</artifactId>
    9. <version>[4.3.2,5.0.0)</version>
    10. </dependency>

    You can import the following libraries as required.

    1. <dependency>
    2. <groupId>commons-codec</groupId>
    3. <artifactId>commons-codec</artifactId>
    4. <version>1.9</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.apache.httpcomponents</groupId>
    8. <artifactId>httpclient</artifactId>
    9. <version>4.5.3</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.google.code.gson</groupId>
    13. <artifactId>gson</artifactId>
    14. <version>2.8.2</version>
    15. </dependency>

Create a client

  1. Add an endpoint to access Image Search. In this example, an endpoint is added to an Image Search instance in the China (Shanghai) region.

    1. DefaultProfile.addEndpoint( "<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com");

    Note: For more information about entering an Image Search endpoint, see Request structure.

  2. Create a profile object. Create a profile object for IClientProfile. This object contains data including the AccessKey ID, AccessKey Secret, and region.

    1. IClientProfile profile = DefaultProfile.getProfile("<region>", "<your-access-key-id>", "<your-access-key-secret>");
  3. Create a client object. Create an IAcsClient object named client from the IClientProfile class. Subsequent responses are retrieved from IAcsClient.

    1. IAcsClient client = new DefaultAcsClient(profile);

Add an image

  1. AddImageRequest request = new AddImageRequest();
  2. //(Required) The name of the Image Search instance.
  3. request.setInstanceName("demo");
  4. //(Required) The product ID can contain up to 512 characters in length.
  5. //A product can have multiple images.
  6. request.setProductId("test");
  7. //(Required) The image name can contain up to 512 characters in length.
  8. // 1. A specific image is identified based on ProductId and PicName.
  9. // 2. If you add multiple images with the same ProductId and PicName, the last add operation prevails and the previous operations are overwritten.
  10. request.setPicName("test");
  11. //(Optional) The image category.
  12. // 1. For product search: If a category is configured, the configured category prevails. If no category is configured, a category prediction is performed. The predicted category results can be obtained in the response.
  13. // 2. For generic search: The parameter value is set to 88888888 regardless of whether a category is set.
  14. request.setCategoryId(1);
  15. byte[] bytes2 = getBytes("/home/admin/demo.jpg");
  16. Base64 base64 = new Base64();
  17. String encodePicContent = base64.encodeToString(bytes2);
  18. //(Required) The image content is encoded by using Base64.
  19. //A maximum image of 2 MB and a 5s transmission wait time are supported. Currently, only JPG and PNG images are supported.
  20. //The image length and width must be greater than or equal to 200 pixels and smaller than or equal to 1,024 pixels. The image cannot contain rotation information.
  21. request.setPicContent(encodePicContent);
  22. //(Optional) Indicates whether subject recognition is required. The default value is true.
  23. // 1. If the parameter is set to true, the system identifies the subject and searches for the identified subject. The subject recognition result is included in the response.
  24. // 2. If this parameter is set to false, the entire image is searched for without subject recognition.
  25. request.setCrop(true);
  26. //(Optional) The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 determine the point in the upper-left corner, and x2 and y2 determine the point in the lower-right corner.
  27. //If you set the Region parameter, the search is conducted based on this parameter regardless of the value of the Crop parameter.
  28. request.setRegion("280,486,232,351");
  29. //(Optional) The integer type attribute, which can be used for filtering during queries. This parameter is returned when you send a query request.
  30. //For example, you can set different IntAttr values for images of different sites or images of different users, and filter the images to implement image isolation during queries.
  31. request.setIntAttr(0);
  32. //(Optional) The string type attribute. This parameter can be up to 128 characters in length. The parameter can be used for filtering during queries. It is returned when you send a query request.
  33. request.setStrAttr("demo");
  34. //(Optional) The user-defined content. The parameter can be up to 4,096 characters in length.
  35. //This parameter is returned when you send a query request. You can add text, such as an image description.
  36. request.setCustomContent("1");
  37. try {
  38. AddImageResponse response = client.getAcsResponse(request)
  39. } catch (ClientException e) {
  40. //An exception is thrown because of an invalid parameter, an unavailable instance, or other reasons.
  41. e.printStackTrace();
  42. }

Search for an image

Search for similar images based on an image.

  1. SearchImageRequest request = new SearchImageRequest();
  2. //(Required) The name of the Image Search instance.
  3. request.setInstanceName("demo");
  4. //(Optional) The search type. Valid values:
  5. // 1. (Default) SearchByPic: search for similar images based on an image.
  6. // 2. SearchByName: search for similar images based on an added image.
  7. // request.setType("SearchByPic");
  8. byte[] bytes2 = getBytes("/home/admin/demo.jpg");
  9. Base64 base64 = new Base64();
  10. String encodePicContent = base64.encodeToString(bytes2);
  11. //The image content, which is encoded by using Base64. A maximum image of 2 MB and a 5s transmission wait time are supported. Currently, only JPG and PNG images are supported.
  12. //The image length and width must be greater than or equal to 200 pixels and smaller than or equal to 1,024 pixels. The image cannot contain rotation information.
  13. // 1. This parameter is required when the value of Type is SearchByPic.
  14. // 2. This parameter is optional when the value of Type is SearchByName.
  15. request.setPicContent(encodePicContent);
  16. //(Optional) The product category.
  17. // 1. For product search: If a category is configured, the configured category prevails. If no category is configured, a category prediction is performed. The predicted category results can be obtained in the response.
  18. // 2. For generic search: The parameter value is set to 88888888 regardless of whether a category is set.
  19. request.setCategoryId(1);
  20. //(Optional) Indicates whether subject recognition is required. The default value is true.
  21. // 1. If the parameter is set to true, the system identifies the subject and searches for the identified subject. The subject recognition result is included in the response.
  22. //2. If this parameter is set to false, the entire image is searched for without subject recognition.
  23. request.setCrop(false);
  24. //(Optional) The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 determine the point in the upper-left corner, and x2 and y2 determine the point in the lower-right corner.
  25. //If you set the Region parameter, the search is conducted based on this parameter regardless of the value of the Crop parameter.
  26. request.setRegion("280,486,232,351");
  27. //(Optional) The total number of the returned records. Valid values: 1 to 100 Default value: 10
  28. request.setNum(2);
  29. //(Optional) The number of the first record that is returned. Valid values: 0 to 499 Default value: 0
  30. request.setStart(1);
  31. //(Optional) The filter condition.
  32. //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.
  33. //Examples:
  34. //1. Filter results based on IntAttr: int_attr>=100
  35. // 2. Filter results based on StrAttr: str_attr! ="value1"
  36. //3. Filter results based on IntAttr and StrAttr: int_attr=1000 AND str_attr="value1"
  37. request.setFilter("int_attr=1");
  38. try {
  39. SearchImageResponse response = client.getAcsResponse(request);
  40. } catch (ClientException e) {
  41. e.printStackTrace();
  42. }

Search for similar images based on an image that is identified by ProductId and PicName.

  1. SearchImageRequest request = new SearchImageRequest();
  2. //(Required) The name of the Image Search instance.
  3. request.setInstanceName("demo");
  4. //(Optional) The search type. Valid values:
  5. //1. (Default) SearchByPic: search for similar images based on an image.
  6. //2. SearchByName: search for similar images based on an added image.
  7. request.setType("SearchByName");
  8. //The product ID.
  9. // 1. The product ID is not required when the value of Type is SearchByPic.
  10. //2. The product ID of the added image is required when the value of Type is SearchByName.
  11. request.setProductId("test");
  12. //The image name.
  13. //1. The image name is not required when the value of Type is SearchByPic.
  14. //2. The name of the added image is required when the value of Type is SearchByName.
  15. request.setPicName("test");
  16. //(Optional) The product category.
  17. // 1. For product search: If a category is configured, the configured category prevails. If no category is configured, a category prediction is performed. The predicted category results can be obtained in the response.
  18. //2. For generic search: The parameter value is set to 88888888 regardless of whether a category is set.
  19. request.setCategoryId(1);
  20. //(Optional) Indicates whether subject recognition is required. The default value is true.
  21. // 1. If the parameter is set to true, the system identifies the subject and searches for the identified subject. The subject recognition result is included in the response.
  22. //2. If this parameter is set to false, the entire image is searched without subject recognition.
  23. request.setCrop(false);
  24. //(Optional) The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 determine the point in the upper-left corner, and x2 and y2 determine the point in the lower-right corner.
  25. //If you set the Region parameter, the search is conducted based on this parameter regardless of the value of the Crop parameter.
  26. request.setRegion("280,486,232,351");
  27. //(Optional) The total number of the returned records. Valid values: 1 to 100 Default value: 10
  28. request.setNum(2);
  29. //(Optional) The number of the first record that is returned. Valid values: 0 to 499 Default value: 0
  30. request.setStart(1);
  31. //(Optional) The filter condition.
  32. //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.
  33. //Examples:
  34. // 1. Filter results based on IntAttr: int_attr>=100
  35. // 2. Filter results based on StrAttr: str_attr! ="value1"
  36. //3. Filter results based on IntAttr and StrAttr: int_attr=1000 AND str_attr="value1"
  37. request.setFilter("int_attr=1");
  38. try {
  39. SearchImageResponse response = client.getAcsResponse(request);
  40. } catch (ClientException e) {
  41. e.printStackTrace();
  42. }

Delete an image

  1. DeleteItemRequest request = new DeleteItemRequest();
  2. //(Required) The name of the Image Search instance.
  3. request.setInstanceName("demo");
  4. //(Required) The product ID.
  5. request.setProductId("test");
  6. //(Optional) The image name. If this parameter is not specified, all images under ProductId are deleted. If this parameter is specified, only the image specified by ProductId and PicName are deleted.
  7. request.setPicName("test");
  8. try {
  9. DeleteImageResponse response = client.getAcsResponse(request);
  10. } catch (ClientException e) {
  11. e.printStackTrace();
  12. }

Appendix

For more information about how to obtain the binary array of the image, see the following sample code.

  1. private static byte[] getBytes(String filePath) {
  2. byte[] buffer = null;
  3. try {
  4. File file = new File(filePath);
  5. FileInputStream fis = new FileInputStream(file);
  6. // The maximum size of an image is 2 MB.
  7. ByteArrayOutputStream bos = new ByteArrayOutputStream(2000 * 1024);
  8. byte[] b = new byte[1000];
  9. int n;
  10. while ((n = fis.read(b)) ! = -1) {
  11. bos.write(b, 0, n);
  12. }
  13. fis.close();
  14. bos.close();
  15. buffer = bos.toByteArray();
  16. } catch (FileNotFoundException e) {
  17. e.printStackTrace();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. return buffer;
  22. }

Download an example for using the SDK

For more information about how to use the Java SDK, click to download a demo.