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
| import boto3
from PIL import Image
import io
s3 = boto3.client('s3')
def lambda_handler(event, context):
"""
Procesa imágenes subidas a S3
"""
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
# Descargar imagen original
response = s3.get_object(Bucket=bucket, Key=key)
image_data = response['Body'].read()
# Procesar imagen
thumbnails = create_thumbnails(image_data)
# Subir thumbnails
for size, thumbnail_data in thumbnails.items():
thumbnail_key = f"thumbnails/{size}/{key}"
s3.put_object(
Bucket=bucket,
Key=thumbnail_key,
Body=thumbnail_data,
ContentType='image/jpeg'
)
def create_thumbnails(image_data):
"""
Crea thumbnails de diferentes tamaños
"""
image = Image.open(io.BytesIO(image_data))
thumbnails = {}
sizes = [(150, 150), (300, 300), (600, 600)]
for width, height in sizes:
# Redimensionar imagen
thumbnail = image.copy()
thumbnail.thumbnail((width, height), Image.Resampling.LANCZOS)
# Convertir a bytes
output = io.BytesIO()
thumbnail.save(output, format='JPEG', quality=85)
thumbnails[f"{width}x{height}"] = output.getvalue()
return thumbnails
|