Wählen Sie Ihre Cookie-Einstellungen aus

Wir verwenden essentielle Cookies und ähnliche Tools, die für die Bereitstellung unserer Website und Services erforderlich sind. Wir verwenden Performance-Cookies, um anonyme Statistiken zu sammeln, damit wir verstehen können, wie Kunden unsere Website nutzen, und Verbesserungen vornehmen können. Essentielle Cookies können nicht deaktiviert werden, aber Sie können auf „Anpassen“ oder „Ablehnen“ klicken, um Performance-Cookies abzulehnen.

Wenn Sie damit einverstanden sind, verwenden AWS und zugelassene Drittanbieter auch Cookies, um nützliche Features der Website bereitzustellen, Ihre Präferenzen zu speichern und relevante Inhalte, einschließlich relevanter Werbung, anzuzeigen. Um alle nicht notwendigen Cookies zu akzeptieren oder abzulehnen, klicken Sie auf „Akzeptieren“ oder „Ablehnen“. Um detailliertere Entscheidungen zu treffen, klicken Sie auf „Anpassen“.

Rufen Sie Amazon Nova Canvas auf Amazon Bedrock auf, um ein Bild zu generieren

Fokusmodus
Rufen Sie Amazon Nova Canvas auf Amazon Bedrock auf, um ein Bild zu generieren - Amazon Bedrock

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Die folgenden Codebeispiele zeigen, wie Amazon Nova Canvas auf Amazon Bedrock aufgerufen wird, um ein Bild zu generieren.

.NET
SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit 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; }
  • Einzelheiten zur API finden Sie InvokeModelunter AWS SDK for .NET API-Referenz.

Java
SDK für Java 2.x
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit 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); } }
  • Einzelheiten zur API finden Sie InvokeModelunter AWS SDK for Java 2.x API-Referenz.

JavaScript
SDK für JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit 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; }); }
  • Einzelheiten zur API finden Sie InvokeModelunter AWS SDK für JavaScript API-Referenz.

Python
SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit dem 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}")
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit 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; }
  • Einzelheiten zur API finden Sie InvokeModelunter AWS SDK for .NET API-Referenz.

Eine vollständige Liste der AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unter. Amazon Bedrock mit einem AWS SDK verwenden Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.

DatenschutzNutzungsbedingungen für die WebsiteCookie-Einstellungen
© 2025, Amazon Web Services, Inc. oder Tochtergesellschaften. Alle Rechte vorbehalten.