OSError:尝试从s3获取图像并打开图像时,无法识别图像文件<_io.BytesIO对象位于0x00000198001B9E08>

时间:2018-12-05 10:38:54

标签: python amazon-s3 aws-lambda

我正在尝试获取jpeg。从s3存储桶中,但出现错误。这是代码的一部分:

s3_client = boto3.client('s3')
bucket = os.environ['encryption_bucket']

def encrypt_zip(event, contex):
    image_key = event['keys']
    response = s3_client.get_object(Bucket= bucket, Key=image_key)
    if response['ResponseMetadata']['HTTPStatusCode'] == 200:
        object_data = response['Body']._raw_stream.data
        print(type(object_data))
        image = Image.open(io.BytesIO(object_data))

错误:

OSError: cannot identify image file <_io.BytesIO object at 0x00000198001B9E08>

第二个问题:尝试从s3存储桶中下载一个对象并保存该图像

if 's3' in event['Records'][0]:
    s3  = event['Records'][0]['s3']
    image_key  = s3['object']['key']
    key_split = str(image_key).split('/')
    job_key = "-".join(key_split)
    bucket = s3['bucket']['name']
    with open(job_key, 'wb') as data:
         client.download_fileobj(bucket, image_key, data)
         set_log("logo image loaded successfully....", False)
    image_path = '/tmp/' + job_key
    image = Image.open(job_key)
    image.save(image_path)

ERROR : OSError: cannot identify image file '8093-C8FE-2403-490B-9050e99b-53a9-4e2f-b9af-9910d5fc9a0f.jpg'

和本地下载图像。无法加载。enter image description here

1 个答案:

答案 0 :(得分:0)

根据您的其他问题(已删除?),您的要求是:

  • 将文件名数组传递给函数
  • /转换为-以简化文件名
  • 您希望使用这些文件创建一个zip文件

因此,它将类似于:

import boto3
import zipfile

s3_client = boto3.client('s3')
bucket = os.environ['encryption_bucket']

def encrypt_zip(event, context):
    key_array = [key.replace('/', '-') for key in event['keys']]

    # Download objects
    for key in key_array:
        response = s3_client.download_file(bucket, key, '/tmp/' + key)

    # Zip objects
    with ZipFile('/tmp/foo.zip', 'w') as myzip:
        for key in key_array:
            myzip.write('/tmp/' + key)
        myzip.close()

    # Put zip file in S3
    s3_client.upload_file('/tmp/foo.zip', bucket, 'foo.zip')

(我还没有测试过,我只是从documentation复制了Zipfile代码,所以我不确定它是否正确。)

我也不确定您要使用/-做什么,因为这取决于传递的键列表以及在S3中调用的对象