このトピックでは、Alibaba Cloud Image Search SDK for Java の使用方法について説明します。

API 操作

操作 説明
Add 画像を追加します。
SearchImageByPic 新しい画像に基づいて類似画像を検索します。
SearchImageByName 画像ギャラリー内の既存の画像の名前に基づいて、類似した画像を検索します。
Delete 画像を削除します。

SDK のデモ

AlibabaCloud Image Search SDK for Java のデモをダウンロードします。

準備

  • Alibaba Cloud SDK をインストールして使用する前に、Alibaba Cloud アカウントが作成され、かつ AccessKey ペアを取得済みであることを確認してください。 詳細については、「AccessKey ペアの作成」をご参照ください。
  • 以下の操作を実行して、Alibaba Cloud Image Search SDK forJava をプロジェクトに追加します。
    AlibabaCloud Image Search SDK for Java を Maven の依存関係としてインポートし、SDK をプロジェクトに追加します。
      <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>imagesearch</artifactId>
            <version>3.0.1</version>
       </dependency>

Add

  • サンプルコード
    import com.aliyun.imagesearch.Client;
    import com.aliyun.imagesearch.models.AddImageAdvanceRequest;
    import com.aliyun.imagesearch.models.AddImageResponse;
    import com.aliyun.imagesearch.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 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 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.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 text, 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 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.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. 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.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 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 instream = new FileInputStream(sampleFile);
            // The image file. 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.picContentObject = inputStream;
            try {
                AddImageResponse response = client.addImageAdvance(request,runtimeOptions);
                System.out.println("success: " + response.success + ". message: " + response.message
                        + ". categoryId: " + response.picInfo.categoryId + ". region:" + response.picInfo.region
                        + ". requestId: " + response.requestId);
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • レスポンスの例
    success: true. message: success.
    categoryId: 3. region:167,467,221,407.
    requestId: 52EC4508-5BC0-4FA0-A85E-B2AD2F3B1EB1

SearchImageByPic

  • サンプルコード
    import com.aliyun.imagesearch.Client;
    import com.aliyun.imagesearch.models.Config;
    import com.aliyun.imagesearch.models.SearchImageByPicAdvanceRequest;
    import com.aliyun.imagesearch.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 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.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. 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.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 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.
            // 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 time-out period cannot exceed 5 seconds. Only JPG and PNG images are supported.
            // For product, 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.requestId);
                System.out.println(response.picInfo.categoryId);
                System.out.println(response.picInfo.region);
              // SearchImageByPicResponse.SearchImageByPicResponseAuctions [] auctions = response.auctions;
                List<SearchImageByPicResponse.SearchImageByPicResponseAuctions> auctions = response.auctions;
                for(SearchImageByPicResponse.SearchImageByPicResponseAuctions auction:auctions) {
                    System.out.println(auction.categoryId + " " + auction.picName + " " + auction.productId + " " + auction.customContent + " " + auction.sortExprValues + " " + auction.strAttr + " " + auction.intAttr);
                }
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • レスポンスの例
    09BE019A-AE3D-4D22-99C9-10533D8AC631
    3
    167,467,221,407
    3 1000 test this is a simple test 5.37633353624177e+24;0 test 56

SearchImageByName

  • サンプルコード
    import com.aliyun.imagesearch.Client;
    import com.aliyun.imagesearch.models.Config;
    import com.aliyun.imagesearch.models.SearchImageByNameRequest;
    import com.aliyun.imagesearch.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 {
            // Configurations
            Config conf = 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 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.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.requestId);
                System.out.println(response.picInfo.categoryId);
                System.out.println(response.picInfo.region);
                List<SearchImageByNameResponse.SearchImageByNameResponseAuctions> auctions = response.auctions;
                for(SearchImageByNameResponse.SearchImageByNameResponseAuctions auction:auctions) {
                    System.out.println(auction.categoryId + " " + auction.picName + " " + auction.productId + " " + auction.customContent + " " + auction.sortExprValues + " " + auction.strAttr + " " + auction.intAttr);
                }
            } catch (TeaException e) {
                System.out.println(e.getCode());
                System.out.println(e.getData());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }
  • レスポンスの例
    8F2441C8-EA05-461B-A4AC-5F5DE25FAC21
    3
    null
    3 1000 test this is a simple test 5.37633353624177e+24;0 test 56

Delete

  • サンプルコード
    import com.aliyun.imagesearch.Client;
    import com.aliyun.imagesearch.models.Config;
    import com.aliyun.imagesearch.models.DeleteImageRequest;
    import com.aliyun.imagesearch.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