【问题标题】:Lambda get image from s3Lambda 从 s3 获取图像
【发布时间】:2016-07-14 09:57:03
【问题描述】:

我正在尝试从我的 S3 存储桶中获取图像并将其返回以在我的 API 网关中使用。 权限设置正确。

 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

但是我得到一个空返回,似乎无法弄清楚如何获取图像。这是正确的方法吗?为什么它不返回我的图像。

【问题讨论】:

    标签: amazon-web-services amazon-s3 aws-lambda boto3 aws-api-gateway


    【解决方案1】:

    您正在下载/tmp/1.png 中的图像文件。您返回的是 download_file() 的返回值,它似乎返回 null。您的 API 网关需要什么数据类型?

    【讨论】:

    • 我已将 API 设置为返回类型 'image/png'
    • 您必须使用某种图像处理库(如 Node.js Lambda 提供的 ImageMagick)来读取文件并返回图像/png。
    • 澄清 helloV 的答案...download_file() 的返回值不是图像本身。图像将被下载到/tmp/1.png,因此您必须返回该文件的内容(而不是返回值)。
    【解决方案2】:

    我在 s3 存储桶中有图像,必须获取或返回该图像, 首先获取图像并编码为 base64 格式并返回该 base64 格式。 从那个 base64 格式,我刚刚解码了 base64 并获取了图像并从 API 返回。 在代码的最后,它返回base64,进入浏览器并搜索'base64 to image', 并粘贴返回的 base64 格式,您将获得您的 s3 存储桶图像。

    以下代码肯定会对某人有所帮助。

    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.
              } 
    

    现在转到 API 网关并创建您的 API。

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 2015-12-18
      • 2021-12-18
      • 2018-01-26
      • 2020-02-01
      • 2019-12-20
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多