I am a beginner so I am hoping to get some help here.
I want create a lambda function (written in Python) that is able to read an image stored in S3 then return the image as a binary file (eg. a byte array). The lambda function is triggered by an API gateway.
Right now, I have setup the API gateway to trigger the Lambda function and it can return a hello message. I also have a gif image stored in a S3 bucket.
import base64
import json
import boto3
s3 = boto.client('s3')
def lambda_handler(event, context):
# TODO implement
bucket = 'mybucket'
key = 'myimage.gif'
s3.get_object(Bucket=bucket, Key=key)['Body'].read()
return {
"statusCode": 200,
"body": json.dumps('Hello from AWS Lambda!!')
}
I really have no idea how to continue. Can anyone advise? Thanks in advance!
you can return Base64 encoded data from your Lambda function with appropriate headers.
Here the updated Lambda function:
import base64
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
bucket = 'mybucket'
key = 'myimage.gif'
image_bytes = s3.get_object(Bucket=bucket, Key=key)['Body'].read()
# We will now convert this image to Base64 string
image_base64 = base64.b64encode(image_bytes)
return {'statusCode': 200,
# Providing API Gateway the headers for the response
'headers': {'Content-Type': 'image/gif'},
# The image in a Base64 encoded string
'body': image_base64,
'isBase64Encoded': True}
For further details and step by step guide, you can refer to this official blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With