Generate an image by invoking Amazon Titan Image on Amazon Bedrock using .NET console application

Introduction

In this article, you will learn how to invoke Amazon Titan Image on Amazon Bedrock to generate an image using the .NET console application.

Note. Refer to this document to learn more about Amazon Titan Image Generator G1.

Prerequisites

  1. Visual Studio 2022
  2. Access to Amazon Bedrock foundation model (Amazon Titan Image Generator G1)
  3. Download and install the AWS Command Line Interface (CLI)
  4. Configure AWS CLI
  5. Install and setup AWS Toolkit for Visual Studio

Steps Involved

Perform the following steps to invoke Amazon Titan Image on Amazon Bedrock to generate an image using the .NET console application in Visual Studio 2022.

  1. Open Visual Studio 2022.
  2. Click File -> New -> Project.
  3. Select the Console App template. Click Next.
  4. Enter the project name and click Next.
  5. Select the .NET 8.0 framework. Click Create.
  6. Add the following NuGet packages.
    AWSSDK.BedrockRuntime
    Newtonsoft.Json
  7. Open Program.cs and replace the code with the following. Refer request and response format to update the InvokeModel call using the Amazon Titan Image based on your need.
    using Amazon;
    using Amazon.BedrockRuntime;
    using Amazon.BedrockRuntime.Model;
    using Amazon.Runtime;
    using Newtonsoft.Json.Linq;
    using System.Text;
    namespace AmazonBedrockImageGenerator
    {
        class Program
        {
            private static readonly string ModelId = "amazon.titan-image-generator-v1";
            private static readonly string FilePath = "C:\\Users\\source\\repos\\generated_image.png";
            private static readonly RegionEndpoint Region = RegionEndpoint.USEast1;
            private static readonly string AccessKeyId = "YOUR_ACCESS_KEY_ID"; // Replace with your access key ID
            private static readonly string SecretAccessKey = "YOUR_SECRET_ACCESS_KEY"; // Replace with your secret access key
    
            static async Task Main(string[] args)
            {
                Console.WriteLine("Generating image. This may take a few seconds...");
                try
                {
                    string base64ImageData = await InvokeModel();
                    if (!string.IsNullOrEmpty(base64ImageData))
                    {
                        DisplayImage(base64ImageData);
                    }
                    else
                    {
                        Console.WriteLine("No image data received.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
    
            public static async Task<string> InvokeModel()
            {
                // Uncomment below two lines, if you are using AccessKeyId and SecretAccessKey
                // var credentials = new BasicAWSCredentials(AccessKeyId, SecretAccessKey);
                // var client = new AmazonBedrockRuntimeClient(credentials, Region);
                var client = new AmazonBedrockRuntimeClient(Region);
    
                var prompt = "Sunrise on the Beach";
                var seed = new Random().Next(1, int.MaxValue);
    
                var nativeRequestTemplate = new JObject
                {
                    { "taskType", "TEXT_IMAGE" },
                    { "textToImageParams", new JObject { { "text", prompt } } },
                    { "imageGenerationConfig", new JObject { { "seed", seed } } }
                };
    
                var jsonString = nativeRequestTemplate.ToString();
                var byteArray = Encoding.UTF8.GetBytes(jsonString);
                var stream = new MemoryStream(byteArray);
    
                try
                {
                    var request = new InvokeModelRequest
                    {
                        ModelId = ModelId,
                        ContentType = "application/json",
                        Accept = "application/json",
                        Body = stream
                    };
    
                    var response = await client.InvokeModelAsync(request);
    
                    using (var reader = new StreamReader(response.Body))
                    {
                        var responseBody = await reader.ReadToEndAsync();
                        var responseObject = JObject.Parse(responseBody);
    
                        Console.WriteLine("Response Body:");                    
    
                        var base64ImageDataToken = responseObject.SelectToken("images[0]");
    
                        if (base64ImageDataToken == null)
                        {
                            Console.WriteLine("Error: Image data not found in the response.");
                            return string.Empty;
                        }
    
                        var base64ImageData = base64ImageDataToken.ToString();
                        return base64ImageData;
                    }
                }
                catch (AmazonServiceException e)
                {
                    Console.WriteLine($"ERROR: Can't invoke '{ModelId}'. Reason: {e.Message}");
                    throw;
                }
            }
    
            public static void DisplayImage(string base64ImageData)
            {
                try
                {
                    var imageBytes = Convert.FromBase64String(base64ImageData);
                    File.WriteAllBytes(FilePath, imageBytes);
                    Console.WriteLine($"Image generated and saved as {FilePath}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error saving image: {ex.Message}");
                }
            }
        }
    }
  8. Hit F5 to execute the application. An image is generated successfully in the specified path.
    Generated Image

Summary

This article describes how to invoke Amazon Titan Image on Amazon Bedrock to generate an image using the .NET console application in Visual Studio 2022.


Similar Articles