1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| # image_processor.py - 图像处理Lambda
import boto3
import io
from PIL import Image
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')
def resize_image_handler(event, context):
"""图像缩放处理"""
for record in event['Records']:
# 解析S3事件
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
# 下载图像
obj = s3_resource.Object(bucket, key)
image_data = obj.get()['Body'].read()
# 处理图像
image = Image.open(io.BytesIO(image_data))
# 生成多个尺寸
sizes = [
('thumbnail', (150, 150)),
('medium', (500, 500)),
('large', (1000, 1000))
]
for size_name, size in sizes:
resized = image.copy()
resized.thumbnail(size, Image.LANCZOS)
# 保存到S3
output_key = f"processed/{size_name}/{key}"
output_buffer = io.BytesIO()
resized.save(output_buffer, format='JPEG', quality=85)
s3_client.put_object(
Bucket=bucket,
Key=output_key,
Body=output_buffer.getvalue(),
ContentType='image/jpeg'
)
# 优化版本:使用预分配内存
def optimized_resize_handler(event, context):
"""优化的图像处理"""
# 预先分配足够的内存
import os
os.environ['PYTHONMALLOC'] = 'malloc'
resize_image_handler(event, context)
|