Files
luntan/app/services/images.py

29 lines
940 B
Python

import os
import uuid
import json
from PIL import Image, ExifTags
def save_image(file_storage, base_dir):
ext = os.path.splitext(file_storage.filename)[1].lower()
name = f"{uuid.uuid4().hex}{ext}"
original_path = os.path.join(base_dir, name)
file_storage.save(original_path)
web_path = os.path.join(base_dir, f"web_{name}")
thumb_path = os.path.join(base_dir, f"thumb_{name}")
with Image.open(original_path) as im:
im_web = im.copy()
im_web.thumbnail((1600, 1600))
im_web.save(web_path)
im_thumb = im.copy()
im_thumb.thumbnail((400, 400))
im_thumb.save(thumb_path)
exif = {}
try:
raw = im.getexif()
for k, v in raw.items():
tag = ExifTags.TAGS.get(k, str(k))
exif[tag] = str(v)
except Exception:
exif = {}
return original_path, web_path, thumb_path, json.dumps(exif)