Files
fet2020/fet2020/gallery/utils.py

92 lines
3.0 KiB
Python

import logging
import os
from django.conf import settings
from PIL import ExifTags, Image, ImageOps
gallery_path = settings.GALLERY["path"]
gallery_thumb_path = settings.GALLERY["thumb_path"]
logger = logging.getLogger(__name__)
size = (320, 320)
valid_images = [".jpg", ".png"]
def get_image_list(folder_name):
file_path = os.path.join(settings.MEDIA_ROOT + gallery_path, folder_name)
img_list = []
if os.path.exists(file_path):
for img in os.listdir(file_path):
ext = os.path.splitext(img)[1]
if ext.lower() not in valid_images:
continue
thumb_path = os.path.join(
settings.MEDIA_ROOT + gallery_thumb_path, folder_name
)
thumb_file_path = os.path.join(thumb_path, f"thumb_{img}")
if os.path.exists(thumb_file_path):
thumb_url = os.path.join(
settings.MEDIA_URL + gallery_thumb_path,
folder_name + "/" + f"thumb_{img}",
)
else:
thumb_url = None
img_dict = {
"title": img,
"image_url": os.path.join(
settings.MEDIA_URL + gallery_path, folder_name + "/" + img
),
"thumb_url": thumb_url,
}
img_list.append(img_dict)
return img_list
def get_folder_list():
if os.path.exists(settings.MEDIA_ROOT + gallery_path):
return next(os.walk(settings.MEDIA_ROOT + gallery_path))[1]
return None
def create_thumbs(folder_path):
file_path = os.path.join(settings.MEDIA_ROOT + gallery_path, folder_path)
thumb_path = os.path.join(settings.MEDIA_ROOT + gallery_thumb_path, folder_path)
if os.path.exists(file_path):
os.makedirs(thumb_path, exist_ok=True)
for f in os.listdir(file_path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
thumb_file_path = os.path.join(thumb_path, f"thumb_{f}")
if os.path.exists(thumb_file_path):
continue
image_path = os.path.join(file_path, f)
logger.info(f"Edit picture '{f}'.")
with Image.open(str(image_path), "r") as image:
if image._getexif() is not None:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == "Orientation":
break
exif = dict(image._getexif().items())
if exif[orientation] == 3:
image = image.rotate(180, expand=True)
elif exif[orientation] == 6:
image = image.rotate(270, expand=True)
elif exif[orientation] == 8:
image = image.rotate(90, expand=True)
thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
thumb.save(thumb_file_path)
logger.info(f"Save thumb 'thumb_{f}'.")