Generating an Image with AWS Bedrock and Stability AI : A Seamless Workflow Using Lambda and S3

Swetha Mudunuri
5 min readJan 1, 2025

--

In this blog, I will walk through the steps to create an automated image generation system using Stability AI, AWS Bedrock, and Amazon S3. With this solution, you can submit a prompt via an API request, generate an image, and retrieve them securely via a pre-signed URL.

Architecture Diagram

What You Will Learn

  • How to use AWS Bedrock to access Stability AI’s model for image generation.
  • How to store the generated images in Amazon S3.
  • How to generate a pre-signed URL to securely share the generated image.
  • How to orchestrate the entire process using AWS Lambda and API Gateway.

Architecture Overview

API Gateway: Receives the user’s request with a prompt to generate an image.

  1. Lambda Function: Processes the request, invokes AWS Bedrock with the prompt, retrieves the image, and uploads it to Amazon S3.
  2. AWS Bedrock: Forwards the prompt to Stability AI’s model and gets the generated image.
  3. S3: Stores the image and generates a pre-signed URL for access.

Prerequisites

Before starting, make sure you have the following:

  • AWS account and access to AWS Bedrock Foundation Models.

Step-by-Step Guide

1. Create an S3 Bucket

First, create an S3 bucket where the generated images will be stored.

  • Go to Amazon S3 in the AWS console.
  • Click Create Bucket.
  • Give your bucket a unique name, for example, image-generation.

2. Create a Lambda Function

Next, create an AWS Lambda function that invokes Bedrock with the user’s prompt, generates an image, and uploads it to S3.

  • Go to Lambda in the AWS console.
  • Click Create Function.
  • Give function name, for example, image-generation-function.
  • Leave the rest to default and click on Create function.
  • Once the function is created, go to Configuration Tab change the timeout value more than 3 sec.
Timeout value

Under configuration , go to the permission tab and click on the role name

Click on Add permissions — add Amazon S3 Full access and AmazonBedrockFullAccess policies.

Permissions

Lambda Function Code:

import json
import boto3
import base64
import datetime

# Initialize AWS clients for Bedrock and S3 services
bedrock_client = boto3.client('bedrock-runtime')
s3_client = boto3.client('s3')

def lambda_handler(event, context):
# Extract the prompt from the incoming event (received from API Gateway)
new_year_message = event['queryStringParameters']['prompt'] # Change to handle query params from API Gateway
print("Prompt received:", new_year_message)

# Invoke the Bedrock model with the provided prompt for image generation
bedrock_response = bedrock_client.invoke_model(
contentType='application/json',
accept='application/json',
modelId='stability.stable-diffusion-xl-v1', # Stability AI model ID
body=json.dumps({
"text_prompts": [{"text": new_year_message}], # Pass the user-provided prompt
"cfg_scale": 10, # Configuration scale for image generation
"steps": 30, # Number of inference steps
"seed": 42 # Seed for reproducibility
})
)

# Parse the response from Bedrock
bedrock_response_json = json.loads(bedrock_response['body'].read())
print("Bedrock response:", bedrock_response_json)

# Get the base64-encoded image data from the response
base64_image_data = bedrock_response_json['artifacts'][0]['base64']

# Decode the base64 image data to binary format
final_image = base64.b64decode(base64_image_data)
print("Image data decoded")

# Generate a unique filename for the image (New Year Poster)
poster_filename = 'new_year_poster_' + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.png'

# Upload the generated image to the S3 bucket
upload_response = s3_client.put_object(
Bucket='S3_bucket_name', #change it to the name of S3 bucket created
Body=final_image,
Key=poster_filename,
ContentType='image/png' # Set the correct content type for the image
)
print(f"Poster uploaded to S3 with key: {poster_filename}")

# Generate a pre-signed URL for accessing the uploaded image
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': 'newyear-poster-generation', 'Key': poster_filename},
ExpiresIn=3600 # URL valid for 1 hour
)
print("Pre-signed URL:", presigned_url)

# Return the pre-signed URL in the Lambda response
return {
'statusCode': 200,
'body': json.dumps({'image_url': presigned_url})
}

Deploy and Test the Lambda Function to test if its working fine.

3. Set Up API Gateway

Now, set up API Gateway to receive requests and trigger the Lambda function.

  • Go to API Gateway in the AWS Console.
  • Create a new API, select REST API and click Build, give a API name and click on Create API
  • Create a resource for API, give it a name.
  • Create a GET method for the API and configure the below settings
  • In the Method request settings, configure the query string parameter (prompt) to pass the user input to Lambda.

Under Integration Request

  • Add the mapping template as below

Now click on Deploy API, stage needs to be selected when deploying an API. API needs to be deployed incase of any changes made to method.

4. Test the System

Once the API Gateway is set up, you can test the system using Postman or any other API testing tool.

You can get the URL from API Gateway console. Go to stages for the corresponding method and copy the invoke URL of the GET method.

You can enter Key — prompt and Value —Image of boy playing football.

5. Access the Image

Open the pre-signed URL returned in the response to view the image generated by Stability AI.

Image generated by Stability AI

Conclusion

By combining AWS Lambda, Bedrock, S3, and Stability AI, we can easily automate the process of generating and storing custom images based on user prompts.

Thank you for Reading

--

--

Swetha Mudunuri
Swetha Mudunuri

Written by Swetha Mudunuri

Cloud and Cybersecurity Professional

No responses yet