すべてのプロダクト
Search
ドキュメントセンター

Image Search:Java SDK

最終更新日:Apr 02, 2026

Image Search の Java SDK を使用すると、REST API を直接呼び出すことなく、画像ギャラリー内の画像の追加、検索、管理、比較ができます。

メソッド

メソッド説明
Add画像ギャラリーに画像を追加します。
SearchImageByPicクエリ画像をアップロードして類似画像を検索します。
SearchImageByNameギャラリー内の既存の画像を使用して類似画像を検索します。
Deleteギャラリーから 1 つ以上の画像を削除します。
UpdateImage既存の画像のメタデータを更新します。
Detailインスタンス情報を取得します。
DumpMetaメタデータをエクスポートするタスクを作成します。
DumpMetaListメタデータのエクスポートタスクを一覧表示します。
BatchTask画像の一括操作のためのバッチタスクを作成します。
BatchTaskListバッチタスクを一覧表示します。
CompareSimilarByImage2 つの画像間の類似度スコアを計算します。
CheckImageExists特定の画像がギャラリーに存在するかどうかを確認します。

前提条件

開始する前に、以下を確認してください:

  1. AccessKey ペアを持つ Alibaba Cloud アカウント。作成するには、「AccessKey ペアの作成」をご参照ください。ご利用のルートアカウントの認証情報ではなく、Resource Access Management (RAM) ユーザーの AccessKey ペアを使用し、AccessKey ID と AccessKey Secret は環境変数に保存してください。ソースコードにハードコーディングしないでください。

  2. Image Search SDK が Maven 依存関係としてご利用のプロジェクトに追加されていること。<dependencies> セクションの pom.xml に以下を追加します:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>imagesearch20201214</artifactId>
        <version>4.3.0</version>
    </dependency>
  3. ご利用の Image Search インスタンスのインスタンス名。インスタンスを購入後、Image Search コンソール のインスタンスリストページでインスタンス名 (インスタンス ID ではありません) を確認します。

クライアントの初期化

すべての例で同じクライアント初期化を使用します。ご利用の Image Search インスタンスがデプロイされているリージョンに合わせて、regionIdendpoint を設定してください。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.teaopenapi.models.Config;

Config authConfig = new Config();

// 環境変数から認証情報をロード
authConfig.accessKeyId = System.getenv("CC_AK_ENV");
authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
authConfig.type = "access_key";

// ご利用のインスタンスのリージョン ID とエンドポイントに置き換えてください
authConfig.regionId = "ap-southeast-1";
authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";

// VPC エンドポイントを使用する場合 (同じリージョン内の ECS インスタンスからのみ):
// authConfig.endpointType = "internal";
// authConfig.endpoint = "imagesearch-vpc.ap-southeast-1.aliyuncs.com";

Client client = new Client(authConfig);
import com.aliyun.imagesearch20201214.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.imagesearch20201214.models.SearchImageByNameRequest;
import com.aliyun.imagesearch20201214.models.SearchImageByNameResponse;
import com.aliyun.tea.TeaException;
import java.util.List;
public class  SearchImageByName{
    public static void main(String[] args) throws Exception {
        // 構成
        Config authConfig = new Config();
        // AK/SK ペアを作成します: https://www.alibabacloud.com/help/resource-access-management/latest/accesskey-pairs-create-an-accesskey-pair-for-a-ram-user
        // Alibaba Cloud アカウントの AccessKey ペアは、すべての API を呼び出す権限を持っています。API の呼び出しや日常の O&M には、Resource Access Management (RAM) ユーザーを使用することを推奨します。
        // AccessKey ID と AccessKey Secret をソースコードに保存しないでください。認証情報が漏洩し、アカウントのすべてのリソースが危険にさらされる可能性があります。
        // この例では、AccessKey ID と AccessKey Secret を環境変数に保存します。必要に応じて設定ファイルに保存することもできます。
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1"; // この値を、ご利用のインスタンスがデプロイされているリージョンに置き換えてください。例えば、インスタンスがシンガポールにデプロイされている場合、regionId を "ap-southeast-1" に設定します。
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com"; // この値を、ご利用のインスタンスのリージョンのエンドポイントに置き換えてください。例えば、インスタンスがシンガポールにデプロイされている場合、endpoint を "imagesearch.ap-southeast-1.aliyuncs.com" に設定します。
        
        // 以下は、内部ネットワーク (VPC) 経由でサービスにアクセスする方法を示しています。
        // 注意: 内部ネットワーク (VPC) アクセスは、ご利用の Image Search インスタンスと同じリージョンにある ECS インスタンスまたはその他のリソースからのみ利用可能です。例えば、ご利用の Image Search インスタンスがシンガポールにデプロイされている場合、VPC エンドポイント経由でサービスにアクセスするには、ご利用の ECS インスタンスまたはその他のリソースもシンガポールにデプロイされている必要があります。そうでない場合、リクエストは失敗します。失敗した場合は、ご利用の ECS インスタンスまたはその他のリソースが Image Search インスタンスと同じリージョンにあることを確認してください。
        // authConfig.endpointType = "internal";  // 内部ネットワーク (VPC) アクセスに必要です。このパラメーターを "internal" に設定します。
        // authConfig.endpoint = "imagesearch-vpc.ap-southeast-1.aliyuncs.com"; // この値を、ご利用のインスタンスのリージョンの VPC エンドポイントに置き換えてください。例えば、インスタンスがシンガポールにデプロイされている場合、endpoint を "imagesearch-vpc.ap-southeast-1.aliyuncs.com" に設定します。
        

        Client client = new Client(authConfig);
        SearchImageByNameRequest request = new SearchImageByNameRequest();
        // 必須。ご利用の Image Search サービスのインスタンス名。注意: これはインスタンス名であり、インスタンス ID ではありません。Alibaba Cloud コンソールのインスタンス情報セクションで確認できます。
        request.instanceName = "XXXXXXXXX";
        // 必須。プロダクト ID。最大長: 256 文字。
        // 1 つのプロダクトに複数の画像を含めることができます。
        request.productId = "test";
        // 必須。画像名。最大長: 256 文字。
        // ProductId + PicName は画像を一位に識別します。
        request.picName = "1000";
        // オプション。製品カテゴリ ID。
        // 1. 商品画像検索の場合: カテゴリを指定すると、システムはそれを使用します。指定しない場合、システムはカテゴリを予測します。予測されたカテゴリはレスポンスから取得できます。
        // 2. 一般的な画像検索の場合: カテゴリを指定したかどうかに関わらず、システムはカテゴリを 88888888 に設定します。
        request.categoryId = 3;
        // オプション。返す結果の数。有効値: 1~100。デフォルト: 10。
        request.num =10;
        // オプション。結果の開始位置。有効値: 0~499。デフォルト: 0。
        request.start =0;
        // オプション。フィルター条件。
        // int_attr でサポートされる演算子: in, not in, >, >=, <, <=, =。str_attr でサポートされる演算子: in, not in, =, !=。複数の条件は AND または OR で組み合わせます。
        // 例:
        //  1. IntAttr によるフィルター: int_attr>=100
        //  2. StrAttr によるフィルター: str_attr!="value1"
        //  3. IntAttr と StrAttr によるフィルター: int_attr=1000 AND str_attr="value1"
        request.filter="int_attr=56 AND str_attr=\"test\" AND int_attr2 in (56)";
        // オプション。類似度スコアのしきい値。
        // このしきい値以上の類似度スコアを持つ画像のみが返されます。有効範囲: 0.00~1.00。小数点以下 2 桁までサポートされます。デフォルト: 0.00。
        request.scoreThreshold="0.54";
        try {
            SearchImageByNameResponse response = client.searchImageByName(request);
            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();
        }
    }
}
VPC エンドポイントは、お客様の Image Search インスタンスと同じリージョンにある Elastic Compute Service (ECS) インスタンスまたはその他のリソースからのみアクセスできます。 異なるリージョンから VPC エンドポイントを使用すると、呼び出しは失敗します。

追加

画像ギャラリーにイメージを追加します。イメージは、productId および picName の組み合わせによって一意に識別されます。同じ productId および picName を持つイメージが既に存在する場合、新しいイメージで上書きされます。

イメージは PNG、JPG、JPEG、BMP、GIF、WebP、TIFF、PPM のいずれかのフォーマットである必要があります。ファイルサイズは 4 MB を超えてはならず、各辺のサイズは 100 ピクセル以上、4,096 ピクセル以下である必要があります。

<your-instance-name> をご利用のインスタンス名に置き換え、アップロードするイメージのファイルパスまたは URL を更新してください。

応答例:

{
  "success": true,
  "message": "success",
  "picInfo": {
    "categoryId": 9,
    "region": "383,681,291,549"
  },
  "requestId": "016D63E3-D0C5-42D3-8879-55E1A705FBA4"
}

categoryId は、システムが選択または確認したカテゴリです。region は、検出された主題領域であり、x1,x2,y1,y2 の形式で表されます。

SearchImageByPic

提供されたクエリ画像に類似した画像を見つけます。類似度スコアでランク付けされた最大 100 件の結果を返します。

<your-instance-name> をご利用のインスタンス名に置き換え、クエリ画像のファイルパスまたは URL を更新してください。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.SearchImageByPicAdvanceRequest;
import com.aliyun.imagesearch20201214.models.SearchImageByPicResponse;
import com.aliyun.imagesearch20201214.models.SearchImageByPicResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

public class SearchImageByPic {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        SearchImageByPicAdvanceRequest request = new SearchImageByPicAdvanceRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.categoryId = 3;                         // オプション。省略すると、システムがカテゴリを予測します。
        request.num = 10;                               // オプション。返す結果の数。有効値: 1–100。デフォルト: 10。
        request.start = 0;                              // オプション。ページネーションのオフセット。有効値: 0–499。デフォルト: 0。
        request.crop = true;                            // オプション。true = 検出された主体に基づいて検索。false = 画像全体を使用。
        request.region = "167,467,221,407";             // オプション。x1,x2,y1,y2 形式の主題領域。指定された場合、crop を上書きします。
        request.filter = "int_attr=56 AND str_attr=\"test\""; // オプション。整数または文字列属性でフィルタリングします。
        request.scoreThreshold = "0.54";                // オプション。類似度のしきい値 (0.00–1.00)。このスコア以上の結果のみが返されます。
        request.distinctProductId = false;              // オプション。true = プロダクト ID ごとに最大 1 つの結果を返します。

        RuntimeOptions runtimeObject = new RuntimeOptions();

        try {
            // オプション 1: URL からアップロード
            // String url = "https://www.example.com/123.jpg";
            // request.picContentObject = new URL(url).openStream();

            // オプション 2: ローカルファイルからアップロード
            InputStream inputStream = new FileInputStream("D:/123.jpg");
            request.picContentObject = inputStream;

            SearchImageByPicResponse response = client.searchImageByPicAdvance(request, runtimeObject);

            // クエリ画像の情報
            System.out.println("requestId: " + response.getBody().requestId);
            System.out.println("categoryId: " + response.getBody().picInfo.categoryId);
            System.out.println("region: " + 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("複数主体の領域:");
            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();
        }
    }
}

レスポンスの例:

{
  "requestId": "09BE019A-AE3D-4D22-99C9-10533D8AC631",
  "picInfo": {
    "categoryId": 3,
    "region": "167,467,221,407",
    "multiRegion": [
      { "region": "112,440,76,387" }
    ]
  },
  "auctions": [
    {
      "categoryId": 3,
      "picName": "1000",
      "productId": "test",
      "customContent": "this is a simple test",
      "score": 1.0,
      "strAttr": "test",
      "intAttr": 56
    }
  ]
}

auctions 内の一致した各画像には、categoryIdpicNameproductIdcustomContentscorestrAttr、および intAttr が含まれます。score1.0 の場合は完全に一致することを示します。multiRegion は、クエリ画像に複数の主体が含まれている場合に検出された追加の主題領域をリストします。

フィルター構文: int_attrinnot in>>=<<=、および = をサポートします。str_attrinnot in=、および != をサポートします。条件は AND または OR で組み合わせます。例:

  • int_attr>=100

  • str_attr!="value1"

  • int_attr=1000 AND str_attr="value1"

SearchImageByName

ギャラリーに既にある画像 (productIdpicName で識別) に類似した画像を見つけます。新しい画像をアップロードするのではなく、既存のギャラリー画像を使用して検索する場合に使用します。

<your-instance-name>productId、および picName をご自身の値に置き換えてください。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.SearchImageByNameRequest;
import com.aliyun.imagesearch20201214.models.SearchImageByNameResponse;
import com.aliyun.imagesearch20201214.models.SearchImageByNameResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;
import java.util.List;

public class SearchImageByName {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        SearchImageByNameRequest request = new SearchImageByNameRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.productId = "test";                     // 必須。クエリ画像のプロダクト ID。
        request.picName = "1000";                       // 必須。クエリ画像の画像名。
        request.categoryId = 3;                         // オプション。省略すると、システムがカテゴリを予測します。
        request.num = 10;                               // オプション。返す結果の数。有効値: 1–100。デフォルト: 10。
        request.start = 0;                              // オプション。ページネーションのオフセット。有効値: 0–499。デフォルト: 0。
        request.filter = "int_attr=56 AND str_attr=\"test\""; // オプション。SearchImageByPic のフィルター構文をご参照ください。
        request.scoreThreshold = "0.54";                // オプション。類似度のしきい値 (0.00–1.00)。

        try {
            SearchImageByNameResponse response = client.searchImageByName(request);

            System.out.println("requestId: " + response.getBody().requestId);
            System.out.println("categoryId: " + response.getBody().picInfo.categoryId);
            System.out.println("region: " + 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();
        }
    }
}

レスポンスの例:

{
  "requestId": "8F2441C8-EA05-461B-A4AC-5F5DE25FAC21",
  "picInfo": {
    "categoryId": 3,
    "region": null
  },
  "auctions": [
    {
      "categoryId": 3,
      "picName": "1000",
      "productId": "test",
      "customContent": "this is a simple test",
      "score": 1.0,
      "strAttr": "test",
      "intAttr": 56
    }
  ]
}

名前で検索する場合、クエリはアップロードされたものではなく既存の保存画像に基づいているため、regionnull になります。

Delete

ギャラリーから画像を削除します。productId を指定してそのプロダクトのすべての画像を削除するか、productIdpicName の両方を指定して単一の画像を削除します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.DeleteImageRequest;
import com.aliyun.imagesearch20201214.models.DeleteImageResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;

public class Delete {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        DeleteImageRequest request = new DeleteImageRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.productId = "test";                     // isDeleteByFilter が false の場合は必須。最大 256 文字。
        request.picName = "1000";                       // オプション。省略すると、プロダクト ID の下のすべての画像が削除されます。
        request.isDeleteByFilter = false;               // オプション。代わりにフィルター式で削除する場合は true に設定します。
        request.filter = "intattr3=xxx";                // isDeleteByFilter が true の場合にのみ使用されます。

        try {
            DeleteImageResponse response = client.deleteImage(request);
            System.out.println(response.getBody().toMap());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getData());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

レスポンスの例:

{
  "Message": "success",
  "RequestId": "994A7095-09AA-127A-873B-A2279261605F",
  "Data": {
    "PicNames": ["82.png"]
  },
  "Code": 0,
  "Success": true
}

PicNames は削除された画像名をリストします。

UpdateImage

既存の画像のメタデータ、具体的には整数属性、文字列属性、またはユーザー定義コンテンツを更新します。productIdpicName は更新する画像を識別し、変更することはできません。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.UpdateImageRequest;
import com.aliyun.imagesearch20201214.models.UpdateImageResponse;
import com.aliyun.teaopenapi.models.Config;

public class UpdateImage {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        UpdateImageRequest request = new UpdateImageRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.setProductId("1");                      // 必須。更新する画像を識別します。
        request.setPicName("1");                        // 必須。更新する画像を識別します。
        request.setIntAttr(1);                          // オプション。フィルタリング用の整数属性。
        request.setStrAttr("test");                     // オプション。文字列属性、最大 128 文字。
        request.setCustomContent("This is a sample description"); // オプション。最大 4,096 文字。

        UpdateImageResponse response = client.updateImage(request);
        System.out.println("requestId: " + response.getBody().requestId
            + ". success: " + response.getBody().success
            + ". message: " + response.getBody().message);
    }
}

レスポンスの例:

{
  "requestId": "AB8AA177-89AB-14D5-BEE0-293C32D5C43A",
  "success": true,
  "message": null
}

Detail

容量、画像数、有効期限など、ご利用の Image Search インスタンスに関する情報を取得します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.DetailRequest;
import com.aliyun.imagesearch20201214.models.DetailResponse;
import com.aliyun.teaopenapi.models.Config;

public class Detail {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        DetailRequest request = new DetailRequest();
        request.instanceName = "<your-instance-name>";  // 必須

        DetailResponse detail = client.detail(request);
        System.out.println(detail.getBody().toMap());
    }
}

レスポンスの例:

{
  "RequestId": "046913C5-942A-1DD2-959F-7CECD790ADB2",
  "Instance": {
    "Name": "xxxx",
    "Region": "cn-shanghai",
    "ServiceType": 0,
    "Capacity": 250,
    "TotalCount": 225320,
    "Qps": 5,
    "UtcCreate": 1633936585000,
    "UtcExpireTime": 1649692800000
  },
  "Success": true
}

キーフィールド: Capacity はインスタンスが保持できる画像の最大数です。TotalCount は現在の画像数です。Qps は 1 秒あたりのクエリ数 (QPS) の上限です。

DumpMeta

画像ギャラリーから Object Storage Service (OSS) ファイルにメタデータをエクスポートする非同期タスクを作成します。DumpMetaList を使用してタスクステータスを確認し、ダウンロード URL を取得します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.DumpMetaRequest;
import com.aliyun.imagesearch20201214.models.DumpMetaResponse;
import com.aliyun.teaopenapi.models.Config;

public class DumpMeta {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        DumpMetaRequest request = new DumpMetaRequest();
        request.instanceName = "<your-instance-name>";  // 必須

        DumpMetaResponse response = client.dumpMeta(request);
        System.out.println(response.getBody().toMap());
    }
}

レスポンスの例:

{
  "RequestId": "FC4191AA-1D5B-1001-9A70-18FBB2BD265B",
  "Data": {
    "Id": 567,
    "DumpMetaStatus": "PROCESSING"
  },
  "Success": true
}

Id の値を保存して、DumpMetaList でタスクステータスを照会します。

DumpMetaList

メタデータのエクスポートタスクを一覧表示し、完了したタスクのダウンロード URL を取得します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.DumpMetaListRequest;
import com.aliyun.imagesearch20201214.models.DumpMetaListResponse;
import com.aliyun.teaopenapi.models.Config;

public class DumpMetaList {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        DumpMetaListRequest request = new DumpMetaListRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.setId(567L);          // オプション。タスク ID でフィルタリングします。
        request.setPageNumber(1);     // オプション。デフォルト: 1。
        request.setPageSize(1);       // オプション。デフォルト: 20。

        DumpMetaListResponse response = client.dumpMetaList(request);
        System.out.println(response.getBody().toMap());
    }
}

レスポンスの例:

{
  "RequestId": "850DFBD9-A179-12FB-B193-2D08ACEA586B",
  "Data": {
    "TotalCount": 1,
    "PageNumber": 1,
    "PageSize": 1,
    "DumpMetaList": [
      {
        "Id": 567,
        "Status": "SUCCESS",
        "Msg": "success",
        "Code": 0,
        "MetaUrl": "https://example.com/x?Expires=x",
        "UtcCreate": 1639969113000,
        "UtcModified": 1639969140000
      }
    ]
  }
}

StatusSUCCESS の場合、MetaUrl を使用してエクスポートされたメタデータファイルをダウンロードします。URL は時間制限があるため、有効期限が切れる前にファイルをダウンロードしてください。

BatchTask

OSS バケットに保存されている画像を画像ギャラリーに追加するためのバッチタスクを作成します。このメソッドを呼び出す前に、OSS パスに increment.meta ファイルを準備してください。ファイル形式については、Image Search ユーザーガイドをご参照ください。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.IncreaseInstanceRequest;
import com.aliyun.imagesearch20201214.models.IncreaseInstanceResponse;
import com.aliyun.teaopenapi.models.Config;

public class BatchTask {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        IncreaseInstanceRequest request = new IncreaseInstanceRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.setBucketName("bucketName");            // 必須。画像を含む OSS バケット。
        request.setPath("/public/xxx");                 // 必須。画像と increment.meta が保存されている OSS パス。/ で始まり、/ で終わらないようにしてください。
        request.setCallbackAddress("http://xxx/xxx");   // オプション。タスク完了時に呼び出されるコールバック URL (http:// または https:// で始まる必要があります)。

        IncreaseInstanceResponse response = client.increaseInstance(request);
        System.out.println(response.getBody().toMap());
    }
}

レスポンスの例:

{
  "RequestId": "F9BAD635-3031-1EBB-BE9E-E9FCB318A28C",
  "Data": {
    "Id": 1470,
    "IncrementStatus": "PROCESSING"
  },
  "Success": true
}

Id の値を保存して、BatchTaskList でタスクを監視します。

BatchTaskList

バッチタスクを一覧表示し、そのステータスを確認します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.IncreaseListRequest;
import com.aliyun.imagesearch20201214.models.IncreaseListResponse;
import com.aliyun.teaopenapi.models.Config;

public class BatchTaskList {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        IncreaseListRequest request = new IncreaseListRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.setId(1470L);                   // オプション。タスク ID でフィルタリングします。
        request.setBucketName("BucketName");    // オプション。OSS バケット名でフィルタリングします。
        request.setPath("/localization/xxxx");  // オプション。OSS パスでフィルタリングします。
        request.setPageNumber(1);               // オプション。デフォルト: 1。
        request.setPageSize(1);                 // オプション。デフォルト: 20。

        IncreaseListResponse response = client.increaseList(request);
        System.out.println(response.getBody().toMap());
    }
}

レスポンスの例:

{
  "RequestId": "56E7E6CC-64AB-17CA-A7CD-1948FB953B8C",
  "Data": {
    "TotalCount": 1,
    "PageNumber": 1,
    "PageSize": 1,
    "Increments": {
      "Instance": [
        {
          "Id": 1464,
          "Status": "NORMAL",
          "Msg": "success",
          "Code": 0,
          "BucketName": "bucketName",
          "Path": "/xx/xx",
          "CallbackAddress": null,
          "ErrorUrl": "https://example.com/xxx?Expires=1670661540&xxx=xx",
          "UtcCreate": 1639107872000,
          "UtcModified": 1639125540000
        }
      ]
    }
  }
}

画像のインポートに失敗した場合、ErrorUrl はエラーをリストしたレポートファイルへのリンクを提供します。

CompareSimilarByImage

画像ギャラリーを使用せずに、2 つの画像の類似度スコアを計算します。一対の画像を直接比較する場合に使用します。

primaryNamesecondaryName のファイルパスまたは URL をご自身の画像に置き換えてください。

package com.aliyun.sample;

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.CompareSimilarByImageAdvanceRequest;
import com.aliyun.imagesearch20201214.models.CompareSimilarByImageResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.teaopenapi.models.Config;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class compareSimilarByImage {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        CompareSimilarByImageAdvanceRequest request = new CompareSimilarByImageAdvanceRequest();
        request.setInstanceName("<your-instance-name>");  // 必須

        try {
            // オプション 1: URL からアップロード
            // String primaryUrl = "https://www.example.com/1.jpg";
            // String secondaryUrl = "https://www.example.com/2.jpg";
            // request.setPrimaryPicContentObject(new URL(primaryUrl).openStream());
            // request.setSecondaryPicContentObject(new URL(secondaryUrl).openStream());

            // オプション 2: ローカルファイルからアップロード
            InputStream primaryInputStream = new FileInputStream("D:/1.jpg");
            InputStream secondaryInputStream = new FileInputStream("D:/2.jpg");
            request.setPrimaryPicContentObject(primaryInputStream);
            request.setSecondaryPicContentObject(secondaryInputStream);

            RuntimeOptions runtimeOptions = new RuntimeOptions();
            CompareSimilarByImageResponse response = client.compareSimilarByImageAdvance(request, runtimeOptions);
            System.out.println(response.getBody().toMap());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getData());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

レスポンスの例:

{
  "Msg": "success",
  "Score": 1.0,
  "RequestId": "5C0F29D6-D5DA-1068-9A6A-F68B07F8E02F",
  "Code": 200,
  "Success": true
}

Score は 0.0 から 1.0 の範囲です。スコア 1.0 は画像が同一であることを意味します。

CheckImageExists

特定の画像がギャラリーに存在するかどうかを、その productIdpicName で識別して確認します。存在する場合、画像のメタデータを返します。

import com.aliyun.imagesearch20201214.Client;
import com.aliyun.imagesearch20201214.models.CheckImageExistsRequest;
import com.aliyun.imagesearch20201214.models.CheckImageExistsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class CheckImageExists {
    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");
        authConfig.type = "access_key";
        authConfig.regionId = "ap-southeast-1";
        authConfig.endpoint = "imagesearch.ap-southeast-1.aliyuncs.com";
        Client client = new Client(authConfig);

        CheckImageExistsRequest request = new CheckImageExistsRequest();
        request.instanceName = "<your-instance-name>";  // 必須
        request.productId = "123";                      // 必須。最大 256 文字。
        request.picName = "123";                        // 必須。最大 256 文字。

        RuntimeOptions runtimeObject = new RuntimeOptions();
        try {
            CheckImageExistsResponse response = client.checkImageExistsWithOptions(request, runtimeObject);
            System.out.println(response.getBody().toMap());
            System.out.println("requestId: " + response.getBody().requestId);
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getData());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

レスポンスの例:

{
  "Msg": "success",
  "RequestId": "xxx-xxx-xxx-xxx-xxxxx",
  "Exists": true,
  "Auctions": {
    "CategoryId": 88888888,
    "ProductId": "123",
    "PicName": "123",
    "CustomContent": null,
    "IntAttr": null,
    "IntAttr2": null,
    "IntAttr3": null,
    "IntAttr4": null,
    "StrAttr": null,
    "StrAttr2": null,
    "StrAttr3": null,
    "StrAttr4": null
  },
  "Code": 0,
  "Success": true
}

Existstrue の場合、Auctions オブジェクトには画像の保存されたメタデータが含まれます。CategoryId88888888 の場合、画像が一般的な画像検索カテゴリでインデックスされたことを示します。