-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_utils.py
More file actions
66 lines (52 loc) · 1.85 KB
/
image_utils.py
File metadata and controls
66 lines (52 loc) · 1.85 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import uuid
from io import BytesIO
from PIL import Image, ImageOps
import boto3
from starlette.concurrency import run_in_threadpool
from config import settings
def _get_s3_client():
return boto3.client(
"s3",
region_name=settings.s3_region,
aws_access_key_id=(
settings.s3_access_key_id.get_secret_value()
if settings.s3_access_key_id
else None
),
aws_secret_access_key=(
settings.s3_secret_access_key.get_secret_value()
if settings.s3_secret_access_key
else None
),
endpoint_url=settings.s3_endpoint_url,
)
def process_profile_image(content: bytes) -> tuple[bytes, str]:
with Image.open(BytesIO(content)) as original:
img = ImageOps.exif_transpose(original)
img = ImageOps.fit(img, (300, 300), method=Image.Resampling.LANCZOS)
if img.mode in ("RGBA", "LA", "P"):
img = img.convert("RGB")
filename = f"{uuid.uuid4().hex}.jpg"
output = BytesIO()
img.save(output, "JPEG", quality=85, optimize=True)
output.seek(0)
return output.read(), filename
def _upload_to_s3(file_bytes: bytes, key: str) -> None:
s3 = _get_s3_client()
s3.upload_fileobj(
BytesIO(file_bytes),
settings.s3_bucket_name,
key,
ExtraArgs={"ContentType": "image/jpeg"},
)
def _delete_from_s3(key: str) -> None:
s3 = _get_s3_client()
s3.delete_object(Bucket=settings.s3_bucket_name, Key=key)
async def upload_profile_image(file_bytes: bytes, filename: str) -> None:
key = f"profile_pics/{filename}"
await run_in_threadpool(_upload_to_s3, file_bytes, key)
async def delete_profile_image(filename: str | None) -> None:
if filename is None:
return
key = f"profile_pics/{filename}"
await run_in_threadpool(_delete_from_s3, key)