Bedrock Image Generation: Custom Blog Images
Blog posts need hero images, but manually creating them is time-consuming and stock photos feel generic. The challenge: generate custom AI images on-demand.
Amazon Bedrock's Titan Image Generator v2 provides text-to-image generation with a simple API. At $0.008 per standard quality image, costs are predictable. The solution: a Python script that generates images, uploads to S3.
The Implementation
def generate_image(prompt, output_key, local_path=None):
"""Generate image with Bedrock and upload to S3"""
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')
body = json.dumps({
"taskType": "TEXT_IMAGE",
"textToImageParams": {
"text": prompt
},
"imageGenerationConfig": {
"numberOfImages": 1,
"quality": "standard",
"height": 768,
"width": 1280,
"cfgScale": 8.0
}
})
response = bedrock.invoke_model(
modelId='amazon.titan-image-generator-v2:0',
body=body
)
result = json.loads(response['body'].read())
image_data = base64.b64decode(result['images'][0])
# Upload to S3
s3 = boto3.client('s3')
s3.put_object(
Bucket=S3_BUCKET,
Key=output_key,
Body=image_data,
ContentType='image/png'
)
update_usage(usage['count'] + 1)
return f"https://{S3_BUCKET}.s3.amazonaws.com/{output_key}"
Results
Each image is custom-tailored to post content, uploaded directly to S3, and tracked automatically. The workflow integrates seamlessly into the blog post creation process with a single command.
The combination of Bedrock's text-to-image API, automatic S3 upload, and usage tracking provides on-demand custom images with predictable costs and zero manual overhead.