我正在使用用 python 2.7x 编写的 AWS Lambda 函数,该函数下载、保存到 /tmp ,然后将图像文件上传回存储桶。
我的图像元数据从带有 http 标头(例如 Content-Type= image/jpeg 等)的原始存储桶开始。
使用 PIL 保存图像后,所有标头都消失了,只剩下 Content-Type = binary/octet-stream
据我所知,由于 PIL 的工作方式,image.save 正在丢失标头。如何保留元数据或至少将其应用到新保存的图像?
我看到过帖子暗示此元数据位于 exif 中,但我尝试从原始文件中获取 exif 信息并应用于保存的文件,但没有成功。无论如何,我不清楚它是否存在于 exif 数据中。
部分代码可以让您了解我在做什么:
def resize_image(image_path):
with Image.open(image_path) as image:
image.save(upload_path, optimize=True)
def handler(event, context):
global upload_path
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode("utf8"))
download_path = '/tmp/{}{}'.format(uuid.uuid4(), file_name)
upload_path = '/tmp/resized-{}'.format(file_name)
s3_client.download_file(bucket, key, download_path)
resize_image(download_path)
s3_client.upload_file(upload_path, '{}resized'.format(bucket), key)
感谢 Sergey,我改为使用 get_object 但响应缺少元数据:
response = s3_client.get_object(Bucket=bucket,Key=key)
响应= {u'Body':,u'AcceptRanges':'字节',u'ContentType':'image/jpeg','ResponseMetadata':{'HTTPStatusCode':200,'RetryAttempts':0,'HostId': 'au30hBMN37/ti0WCfDqlb3t9ehainumc9onVYWgu+CsrHtvG0u/zmgcOIvCCBKZgQrGoooZoW9o=','RequestId':'1A94D7F01914A787','HTTPHeaders':{'内容长度':'84053','x-amz-id -2': 'au30hBMN37/ti0WCfDqlb3t9ehainumc9onVYWgu+CsrHtvG0u /zmgcOIvCCBKZgQrGoooZoW9o=', '接受范围': '字节', '过期': 'Sun, 2034 年 1 月 1 日 00:00:00 GMT', '服务器': 'AmazonS3', '最后修改': '星期五, 2016 年 12 月 23 日 15:21:56 GMT', 'x-amz-request-id': '1A94D7F01914A787', 'etag': '"9ba59e5457da0dc40357f2b53715619d"', '缓存控制': 'max-age=2592000,public' , '日期': '2016 年 12 月 23 日星期五 15:21:58 GMT', '内容类型': 'image/jpeg'}}, u'LastModified': datetime.datetime(2016, 12, 23, 15, 21, 56, tzinfo=tzutc()), u'ContentLength': 84053, u'过期': datetime.datetime(2034, 1, 1, 0, 0, tzinfo=tzutc()), u'ETag': ' "9ba59e5457da0dc40357f2b53715619d"', u'CacheControl': 'max-age=2592000,public', u'元数据': {}}
如果我使用:
元数据 = 响应['ResponseMetadata']['HTTPHeaders']
元数据 = {'内容长度':'84053','x-amz-id-2':'f5UAhWzx7lulo3cMVF8hdVRbHnhdnjHWRDl + LDFkYm9pubjL0A01L5yWjgDjWRE4TjRnjqDeA0U =','接受范围':'字节','过期':' 2034 年 1 月 1 日,星期日00:00:00 GMT', '服务器': 'AmazonS3', '上次修改': '2016 年 12 月 23 日星期五 15:47:09 GMT', 'x-amz-request-id': '4C69DF8A58EF3380', 'etag': '"9ba59e5457da0dc40357f2b53715619d"', '缓存控制': 'max-age=2592000,public', '日期': '2016 年 12 月 23 日星期五 15:47:10 GMT', '内容类型': '图像/jpeg'}
使用 put_object 保存
s3_client.put_object(Bucket=bucket+'resized',Key=key, Metadata=metadata, Body=downloadfile)
在 s3 中创建大量额外元数据,包括它不将内容类型保存为 image/jpeg,而是保存为二进制/八位字节流,并且它确实创建元数据 x-amz-meta-content-type = image/jpeg