Repository navigation
Expand file tree
/
Copy pathlambda_function.py
More file actions
49 lines (38 loc) · 1.7 KB
/
Copy pathlambda_function.py
File metadata and controls
49 lines (38 loc) · 1.7 KB
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
import boto3
import io
from PIL import Image
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Bucket ismini tam olarak buraya yazıyoruz
dest_bucket = "proje-optimized-images-fsmadeit"
try:
# S3'ten gelen her kayıt için dön
for record in event['Records']:
source_bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
print(f"Islem basliyor: {key}")
# 1. Dosyayı oku
response = s3.get_object(Bucket=source_bucket, Key=key)
image_content = response['Body'].read()
# 2. Resmi aç ve küçült
with Image.open(io.BytesIO(image_content)) as img:
# Orijinal formatı koru (PNG, JPEG vb.)
img_format = img.format
# Boyutu yarıya indir
img.thumbnail((img.width // 2, img.height // 2))
# 3. Belleğe yaz
buffer = io.BytesIO()
img.save(buffer, format=img_format)
buffer.seek(0)
# 4. Diğer bucket'a yükle
s3.put_object(
Bucket=dest_bucket,
Key=f"optimized-{key}",
Body=buffer,
ContentType=response.get('ContentType', 'image/jpeg')
)
print(f"Basarili: optimized-{key}")
return {'statusCode': 200, 'body': 'Basariyla tamamlandi'}
except Exception as e:
print(f"HATA DETAYI: {str(e)}")
return {'statusCode': 500, 'body': str(e)}