列出專案中的圖片

這個範例說明如何列出指定專案中的所有可用映像檔。

程式碼範例

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 Compute Engine Java API 參考說明文件

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.ListImagesRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ListImages {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";

    listImages(projectId);
  }

  // Retrieve a list of images available in given project.
  public static List<Image> listImages(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ImagesClient client = ImagesClient.create()) {
      ListImagesRequest request = ListImagesRequest.newBuilder()
              .setProject(projectId)
              .build();

      ArrayList<Image> images = Lists.newArrayList(client.list(request).iterateAll());

      System.out.printf("'%s' images has been retrieved successfully", images.size());

      return images;
    }
  }
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 Compute Engine Python API 參考說明文件

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1


def list_images(project_id: str) -> Iterable[compute_v1.Image]:
    """
    Retrieve a list of images available in given project.

    Args:
        project_id: project ID or project number of the Cloud project you want to list images from.

    Returns:
        An iterable collection of compute_v1.Image objects.
    """
    image_client = compute_v1.ImagesClient()
    return image_client.list(project=project_id)

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器