-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_utils.py
More file actions
35 lines (22 loc) · 883 Bytes
/
Copy pathimage_utils.py
File metadata and controls
35 lines (22 loc) · 883 Bytes
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
import uuid
from io import BytesIO
from pathlib import Path
from PIL import Image, ImageOps
PROFILE_PICS_DIR = Path("media/profile_pics")
def process_profile_image(content: 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"
filepath = PROFILE_PICS_DIR / filename
PROFILE_PICS_DIR.mkdir(parents=True, exist_ok=True)
img.save(filepath, "JPEG", quality=85, optimize=True)
return filename
def delete_profile_image(filename: str | None) -> None:
if filename is None:
return
filepath = PROFILE_PICS_DIR / filename
if filepath.exists():
filepath.unlink()