Cookie の設定を選択する

当社は、当社のサイトおよびサービスを提供するために必要な必須 Cookie および類似のツールを使用しています。当社は、パフォーマンス Cookie を使用して匿名の統計情報を収集することで、お客様が当社のサイトをどのように利用しているかを把握し、改善に役立てています。必須 Cookie は無効化できませんが、[カスタマイズ] または [拒否] をクリックしてパフォーマンス Cookie を拒否することはできます。

お客様が同意した場合、AWS および承認された第三者は、Cookie を使用して便利なサイト機能を提供したり、お客様の選択を記憶したり、関連する広告を含む関連コンテンツを表示したりします。すべての必須ではない Cookie を受け入れるか拒否するには、[受け入れる] または [拒否] をクリックしてください。より詳細な選択を行うには、[カスタマイズ] をクリックしてください。

Amazon Bedrock で Amazon Nova Canvas を呼び出してイメージを生成する - AWS SDK コードの例

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 AWS

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 AWS

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Amazon Bedrock で Amazon Nova Canvas を呼び出してイメージを生成する

次のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出してイメージを生成する方法を示しています。

.NET
SDK for .NET
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon Nova Canvas でイメージを作成します。

// Use the native inference API to create an image with Amazon Nova Canvas. using System; using System.IO; using System.Text.Json; using System.Text.Json.Nodes; using Amazon; using Amazon.BedrockRuntime; using Amazon.BedrockRuntime.Model; // Create a Bedrock Runtime client in the AWS Region you want to use. var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); // Set the model ID. var modelId = "amazon.nova-canvas-v1:0"; // Define the image generation prompt for the model. var prompt = "A stylized picture of a cute old steampunk robot."; // Create a random seed between 0 and 858,993,459 int seed = new Random().Next(0, 858993460); //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { taskType = "TEXT_IMAGE", textToImageParams = new { text = prompt }, imageGenerationConfig = new { seed, quality = "standard", width = 512, height = 512, numberOfImages = 1 } }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelRequest() { ModelId = modelId, Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)), ContentType = "application/json" }; try { // Send the request to the Bedrock Runtime and wait for the response. var response = await client.InvokeModelAsync(request); // Decode the response body. var modelResponse = await JsonNode.ParseAsync(response.Body); // Extract the image data. var base64Image = modelResponse["images"]?[0].ToString() ?? ""; // Save the image in a local folder string savedPath = AmazonNovaCanvas.InvokeModel.SaveBase64Image(base64Image); Console.WriteLine($"Image saved to: {savedPath}"); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「AWS SDK for .NET API リファレンス」の「InvokeModel」を参照してください。

Java
SDK for Java 2.x
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon Nova Canvas でイメージを作成します。

import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse; import java.security.SecureRandom; import java.util.Base64; import static com.example.bedrockruntime.libs.ImageTools.displayImage; /** * This example demonstrates how to use Amazon Nova Canvas to generate images. * It shows how to: * - Set up the Amazon Bedrock runtime client * - Configure the image generation parameters * - Send a request to generate an image * - Process the response and handle the generated image */ public class InvokeModel { public static byte[] invokeModel() { // Step 1: Create the Amazon Bedrock runtime client // The runtime client handles the communication with AI models on Amazon Bedrock BedrockRuntimeClient client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Step 2: Specify which model to use // For the latest available models, see: // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html String modelId = "amazon.nova-canvas-v1:0"; // Step 3: Configure the generation parameters and create the request // First, set the main parameters: // - prompt: Text description of the image to generate // - seed: Random number for reproducible generation (0 to 858,993,459) String prompt = "A stylized picture of a cute old steampunk robot"; int seed = new SecureRandom().nextInt(858_993_460); // Then, create the request using a template with the following structure: // - taskType: TEXT_IMAGE (specifies text-to-image generation) // - textToImageParams: Contains the text prompt // - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.) // For a list of available request parameters, see: // https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html String request = """ { "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "{{prompt}}" }, "imageGenerationConfig": { "seed": {{seed}}, "quality": "standard" } }""" .replace("{{prompt}}", prompt) .replace("{{seed}}", String.valueOf(seed)); // Step 4: Send and process the request // - Send the request to the model using InvokeModelResponse // - Extract the Base64-encoded image from the JSON response // - Convert the encoded image to a byte array and return it try { InvokeModelResponse response = client.invokeModel(builder -> builder .modelId(modelId) .body(SdkBytes.fromUtf8String(request)) ); JSONObject responseBody = new JSONObject(response.body().asUtf8String()); // Convert the Base64 string to byte array for better handling return Base64.getDecoder().decode( new JSONPointer("/images/0").queryFrom(responseBody).toString() ); } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s%n", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { System.out.println("Generating image. This may take a few seconds..."); byte[] imageData = invokeModel(); displayImage(imageData); } }
  • API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「InvokeModel」を参照してください。

JavaScript
SDK for JavaScript (v3)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon Nova Canvas でイメージを作成します。

import { BedrockRuntimeClient, InvokeModelCommand, } from "@aws-sdk/client-bedrock-runtime"; import { saveImage } from "../../utils/image-creation.js"; import { fileURLToPath } from "node:url"; /** * This example demonstrates how to use Amazon Nova Canvas to generate images. * It shows how to: * - Set up the Amazon Bedrock runtime client * - Configure the image generation parameters * - Send a request to generate an image * - Process the response and handle the generated image * * @returns {Promise<string>} Base64-encoded image data */ export const invokeModel = async () => { // Step 1: Create the Amazon Bedrock runtime client // Credentials will be automatically loaded from the environment const client = new BedrockRuntimeClient({ region: "us-east-1" }); // Step 2: Specify which model to use // For the latest available models, see: // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html const modelId = "amazon.nova-canvas-v1:0"; // Step 3: Configure the request payload // First, set the main parameters: // - prompt: Text description of the image to generate // - seed: Random number for reproducible generation (0 to 858,993,459) const prompt = "A stylized picture of a cute old steampunk robot"; const seed = Math.floor(Math.random() * 858993460); // Then, create the payload using the following structure: // - taskType: TEXT_IMAGE (specifies text-to-image generation) // - textToImageParams: Contains the text prompt // - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.) // For a list of available request parameters, see: // https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html const payload = { taskType: "TEXT_IMAGE", textToImageParams: { text: prompt, }, imageGenerationConfig: { seed, quality: "standard", }, }; // Step 4: Send and process the request // - Embed the payload in a request object // - Send the request to the model // - Extract and return the generated image data from the response try { const request = { modelId, body: JSON.stringify(payload), }; const response = await client.send(new InvokeModelCommand(request)); const decodedResponseBody = new TextDecoder().decode(response.body); // The response includes an array of base64-encoded PNG images /** @type {{images: string[]}} */ const responseBody = JSON.parse(decodedResponseBody); return responseBody.images[0]; // Base64-encoded image data } catch (error) { console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`); throw error; } }; // If run directly, execute the example and save the generated image if (process.argv[1] === fileURLToPath(import.meta.url)) { console.log("Generating image. This may take a few seconds..."); invokeModel() .then(async (imageData) => { const imagePath = await saveImage(imageData, "nova-canvas"); // Example path: javascriptv3/example_code/bedrock-runtime/output/nova-canvas/image-01.png console.log(`Image saved to: ${imagePath}`); }) .catch((error) => { console.error("Execution failed:", error); process.exitCode = 1; }); }
  • API の詳細については、「AWS SDK for JavaScript API リファレンス」の「InvokeModel」を参照してください。

Python
SDK for Python (Boto3)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon Nova Canvas を使用してイメージを作成します。

# Use the native inference API to create an image with Amazon Nova Canvas import base64 import json import os import random import boto3 # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID. model_id = "amazon.nova-canvas-v1:0" # Define the image generation prompt for the model. prompt = "A stylized picture of a cute old steampunk robot." # Generate a random seed between 0 and 858,993,459 seed = random.randint(0, 858993460) # Format the request payload using the model's native structure. native_request = { "taskType": "TEXT_IMAGE", "textToImageParams": {"text": prompt}, "imageGenerationConfig": { "seed": seed, "quality": "standard", "height": 512, "width": 512, "numberOfImages": 1, }, } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract the image data. base64_image_data = model_response["images"][0] # Save the generated image to a local folder. i, output_dir = 1, "output" if not os.path.exists(output_dir): os.makedirs(output_dir) while os.path.exists(os.path.join(output_dir, f"nova_canvas_{i}.png")): i += 1 image_data = base64.b64decode(base64_image_data) image_path = os.path.join(output_dir, f"nova_canvas_{i}.png") with open(image_path, "wb") as file: file.write(image_data) print(f"The generated image has been saved to {image_path}")
  • API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「InvokeModel」を参照してください。

SDK for .NET
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon Nova Canvas でイメージを作成します。

// Use the native inference API to create an image with Amazon Nova Canvas. using System; using System.IO; using System.Text.Json; using System.Text.Json.Nodes; using Amazon; using Amazon.BedrockRuntime; using Amazon.BedrockRuntime.Model; // Create a Bedrock Runtime client in the AWS Region you want to use. var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); // Set the model ID. var modelId = "amazon.nova-canvas-v1:0"; // Define the image generation prompt for the model. var prompt = "A stylized picture of a cute old steampunk robot."; // Create a random seed between 0 and 858,993,459 int seed = new Random().Next(0, 858993460); //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { taskType = "TEXT_IMAGE", textToImageParams = new { text = prompt }, imageGenerationConfig = new { seed, quality = "standard", width = 512, height = 512, numberOfImages = 1 } }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelRequest() { ModelId = modelId, Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)), ContentType = "application/json" }; try { // Send the request to the Bedrock Runtime and wait for the response. var response = await client.InvokeModelAsync(request); // Decode the response body. var modelResponse = await JsonNode.ParseAsync(response.Body); // Extract the image data. var base64Image = modelResponse["images"]?[0].ToString() ?? ""; // Save the image in a local folder string savedPath = AmazonNovaCanvas.InvokeModel.SaveBase64Image(base64Image); Console.WriteLine($"Image saved to: {savedPath}"); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「AWS SDK for .NET API リファレンス」の「InvokeModel」を参照してください。

プライバシーサイト規約Cookie の設定
© 2025, Amazon Web Services, Inc. or its affiliates.All rights reserved.