python - AWS lambda 一次放置对象多个图像
问题描述
我正在尝试将源图像的大小调整为多个维度+扩展。
例如:当我上传源图像时,比如说 abc.jpg,我需要使用 s3 事件触发器将其调整为不同尺寸的 .jpg 和 .webp,例如abc_320.jpg、abc_320.webp、abc_640.jpg、abc_640.webp 。因此,使用我当前的 python lambda 处理程序,我可以通过多次put_object
调用目标存储桶来做到这一点,但我想让它更加优化,因为将来我的维度+扩展可能会增加。那么如何一次调用将所有调整大小的图像存储到目标存储桶?
当前的 Lambda 处理程序:
import json
import boto3
import os
from os import path
from io import BytesIO
from PIL import Image
# boto3 S3 initialization
s3_client = boto3.client("s3")
def lambda_handler(event, context):
destination_bucket_name = 'destination-bucket'
# event contains all information about uploaded object
print("Event :", event)
# Bucket Name where file was uploaded
source_bucket_name = event['Records'][0]['s3']['bucket']['name']
# Filename of object (with path)
dest_bucket_perfix = 'resized'
file_key_name = event['Records'][0]['s3']['object']['key']
image_obj = s3_client.get_object(Bucket=source_bucket_name, Key=file_key_name)
image_obj = image_obj.get('Body').read()
img = Image.open(BytesIO(image_obj))
dimensions = [320, 640]
# Checking the extension and
img_extension = path.splitext(file_key_name)[1].lower()
extension_dict = {".jpg":"JPEG", ".png":"PNG", ".jpeg":"JPEG"}
extensions = ["WebP"]
if img_extension in extension_dict.keys():
extensions.append(extension_dict[img_extension])
print ("test-1")
for dimension in dimensions:
WIDTH = HEIGHT = dimension
for extension in extensions:
resized_img = img.resize((WIDTH, HEIGHT))
buffer = BytesIO()
resized_img.save(buffer, extension)
buffer.seek(0)
# I don't want to use this put_object in loop <<<---
s3_client.put_object(Bucket=destination_bucket_name, Key=file_key_name.replace("upload", dest_bucket_perfix, 1), Body=buffer)
return {
'statusCode': 200,
'body': json.dumps('Hello from S3 events Lambda!')
}
你可以看到我需要调用put_object
维度+扩展的每次迭代,这是昂贵的。我还考虑过多线程和压缩解决方案,但正在寻找其他可能的想法/解决方案
解决方案
Amazon S3 API 调用每次调用只允许上传一个对象。
但是,您可以将程序修改为多线程并并行上传对象。
推荐阅读
- javascript - 为每个 React 组件指定不同的 momentJS 语言环境
- snowflake-cloud-data-platform - 错误:将数据从 Oracle 插入到 Snowflake 时超过 255 个字符的最大长度限制?
- swift - 如何:检测可观察对象是否在 RxSwift 中的特定时间未发出任何事件
- symfony4 - 您请求了一个不存在的服务“fos_user.manager”
- ios - 我在哪里可以找到 iPhone 模拟器上的 MyDocuments 文件夹?
- python - 我的 while 循环只在第二次而不是第一次工作
- javascript - AJAX 仅发布第一个表单
- maven - Maven测试不显示测试结果
- javascript - HTML 文件未在浏览器中加载
- language-server-protocol - textDocument/Definition、textDocument/implementation 有什么区别?