本文来源:
主要是其试验经过。
Task1:创建两个S3
命名分别为images-NUMBER, images-NUMBER-resized
找到一张大图,名为HappyFace.jpg,上传到images-NUMBER
Task2:创建lambda函数
默认设置,填写名称Create-Thumbnail,Runtime:python3.7
在Choose or create an execution role中选择
Execution role:Using an existing role
Existing role:lambda-execution-role
这个role会给lambda函数访问和读写S3的权限
点击Add trigger,选择trigger:s3,Bucket选择images-NUMBER,EventType为all object create events然后Add
图中点击Create-Thumbnail,代码里选择upload a file from s3
https://s3-us-west-2.amazonaws.com/us-west-2-aws-training/awsu-spl/spl-88/2.3.7.prod/scripts/CreateThumbnail.zip
它的意思是
import boto3
import os
import sys
import uuid
from PIL import Image
import PIL.Image
s3_client = boto3.client('s3')
def resize_image(image_path, resized_path):
with Image.open(image_path) as image:
image.thumbnail((128, 128))
image.save(resized_path)
def handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)
upload_path = '/tmp/resized-{}'.format(key)
s3_client.download_file(bucket, key, download_path)
resize_image(download_path, upload_path)
s3_client.upload_file(upload_path, '{}-resized'.format(bucket), key)
在Basic settings中,编辑
Description:Create a thumbnail-sized image
Handler:CreateThumbnail.handler
保存。Lambda函数至此已配置好。
Task3:测试lambda函数
点击上方Test按钮,配置
Event template:搜索“Amazon S3 Put“
Event name:Upload
在下方代码中替换example-bucket的两处内容为images-NUMBER。
替换test/key的一处,为HappyFace.jpg
点击Create。随后开始Test
在images-NUMBER-resized查看新图片。
<完>
附:
AWS Lambda文档:https://docs.aws.amazon.com/lambda/index.html