user3024827
user3024827

Reputation: 1258

Lambda get image from s3

I am trying to get an image from my S3 bucket and return it for use in my API gateway. Permissions are set correctly.

 import boto3

s3 = boto3.resource('s3')

def handler(event, context):
   image = s3.meta.client.download_file('mybucket', 'email-sig/1.png', '/tmp/1.png')
   return image

however I am getting a null return and cannot seem to figure out how to get the image. Is this the correct approach, and why is it not returning my image.

Upvotes: 0

Views: 9486

Answers (2)

Suraj Kulkarni
Suraj Kulkarni

Reputation: 181

I have images in s3 bucket and have to get or return that images, First get the image and encoded to base64 format and the return that base64 format. From that base64 format, I have just decoded base64 and Got the image and returned from API. At the end of the code, it returns base64, go to the browser and search 'base64 to image', and paste that returning base64 format you will get your s3 bucket image.

The following code will sure help someone.

import boto3
import base64
from boto3 import client
def lambda_handler(event, context):

    user_download_img ='Name Of Your Image in S3'

    print('user_download_img ==> ',user_download_img)

    s3 = boto3.resource('s3')

    bucket = s3.Bucket(u'Your-Bucket-Name') 

    obj = bucket.Object(key=user_download_img)      #pass your image Name to key

    response = obj.get()     #get Response

    img = response[u'Body'].read()        # Read the respone, you can also print it.

    print(type(img))                      # Just getting type.

    myObj = [base64.b64encode(img)]          # Encoded the image to base64

    print(type(myObj))            # Printing the values

    print(myObj[0])               # get the base64 format of the image

    print('type(myObj[0]) ================>',type(myObj[0]))

    return_json = str(myObj[0])           # Assing to return_json variable to return.  

    print('return_json ========================>',return_json)

    return_json = return_json.replace("b'","")          # repplace this 'b'' is must to get absoulate image.

    encoded_image = return_json.replace("'","")   

    return {
            'status': 'True',
           'statusCode': 200,
           'message': 'Downloaded profile image',
           'encoded_image':encoded_image          # returning base64 of your image which in s3 bucket.
          } 

Now go to API gateway and create your API.

Upvotes: 1

helloV
helloV

Reputation: 52375

You are downloading the image file which is in /tmp/1.png. What you are returning is the return value of download_file() which seems to be returning null. What data type does your API gateway expect?

Upvotes: 1

Related Questions