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

API 操作

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

準備

  • Alibaba Cloud SDK をインストールして使用する前に、Alibaba Cloud アカウントが作成済みで、AccessKey ペアを取得済みであることを確認してください。 詳細については、「t1938336.html#task968」をご参照ください。
  • 次の操作を実行して、Alibaba Cloud Image Search SDK forJava をプロジェクトに追加します。
    Alibaba Cloud Image Search SDK for Java を Maven 依存関係としてインポートし、SDK をプロジェクトに追加します。
    <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>
    ビジネスニーズに基づいて、次のライブラリをインポートできます。
    <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>

クライアントの作成

  1. Image Search インスタンスにアクセスするためのエンドポイントを指定します。 この例では、Image Search インスタンスは中国 (上海) リージョンにあります。
    DefaultProfile.addEndpoint( "<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com");
    エンドポイントの詳細については、「リクエストの構文」をご参照ください。
  2. プロファイルオブジェクトを作成します。 IClientProfile のプロファイルオブジェクトを作成します。 このオブジェクトには、AccessKey ID、AccessKey Secret、リージョンに関する情報が含まれています。
    IClientProfile profile = DefaultProfile.getProfile("<region>", "<your-access-key-id>", "<your-access-key-secret>");
  3. クライアントを作成します。 IClientProfile クラスから client という名前の IAcsClient オブジェクトを作成します。 後続のレスポンスは IAcsClient から取得されます。
    IAcsClient client = new DefaultAcsClient(profile);

画像の追加

次のコード例は、画像を追加するために使用されます。
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();
    }

画像の検索

  • 新しい画像に基づいて類似の画像を検索します。
    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();
        }
  • ProductId パラメーターと PicName パラメーターで識別されている既存の画像に基づいて類似の画像を検索します。
    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();
        }

画像の削除

次のサンプルコードは、画像を削除するために使用されます。
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();
    }

追加情報

次のコード例は、画像のバイナリ配列を取得するために使用されます。
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;
    }

SDK デモのダウンロード

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