I'm trying to get my image from S3 bucket and return it. Here's the code:
import base64
import boto3
import json
import random
s3 = boto3.client('s3')
def lambda_handler(event, context):
number = random.randint(0,1)
if number == 1:
response = s3.get_object(
Bucket='bucket-name',
Key='image.png',
)
image = response['Body'].read()
return {
'headers': { "Content-Type": "image/png" },
'statusCode': 200,
'body': base64.b64encode(image).decode('utf-8'),
'isBase64Encoded': True
}
else:
return {
'headers': { "Content-type": "text/html" },
'statusCode': 200,
'body': "<h1>This is text</h1>",
}
When I hit my endpoint, an image of a tiny white box is returned. I know image.png
exists in my bucket, and when I use the web GUI to open it in my browser, the image is loaded properly. What am I exactly doing wrong here? And in case it matters, here's how I'm uploading the image to S3 (from another Lambda):
...
# Prepare image for S3
buffer = io.BytesIO()
my_image.save(buffer, 'PNG')
buffer.seek(0) # Rewind pointer back to start
response = s3.put_object(
Bucket=S3_BUCKET_NAME,
Key=f'{S3_KEY}{filename}.png',
Body=buffer,
ContentType='image/png',
)
...
In the above code, my_image
is just an image I created using the PIL
library.
Thanks for any help!
CodePudding user response:
Here it is how I do this:
Your lambda with corrected body
:
import base64
import boto3
import json
import random
s3 = boto3.client('s3')
def lambda_handler(event, context):
response = s3.get_object(
Bucket='bucket-name',
Key='image.png',
)
image = response['Body'].read()
return {
'headers': { "Content-Type": "image/png" },
'statusCode': 200,
'body': base64.b64encode(image),
'isBase64Encoded': True
}
API gateway settings
Integration Request