Files
NibasaViewer/viewer/utils.py

55 lines
1.9 KiB
Python
Raw Normal View History

2023-07-30 18:55:12 -04:00
# Standard library imports.
from pathlib import Path
# External library imports.
from PIL import Image
# Django imports.
from django.conf import settings
2023-07-30 19:07:32 -04:00
###########################################################################################
# Constants. #
###########################################################################################
THUMB_SIZE = (128, 128)
# Supported image extensions for fast file filtering (avoids costly MIME-type detection)
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.tif', '.svg'}
2023-07-30 18:55:12 -04:00
###########################################################################################
# Helper functions. #
###########################################################################################
2025-01-15 15:14:40 -04:00
def is_image_file(path):
"""
Fast image detection using file extension instead of MIME-type checking.
:param path: A pathlib.Path instance or string path to check.
:return: True if the file extension matches a known image format.
"""
if isinstance(path, str):
path = Path(path)
return path.suffix.lower() in IMAGE_EXTENSIONS
2023-07-30 18:55:12 -04:00
def make_thumbnail(image):
"""
Creates a thumbnail in the corresponding THUMBNAILS_ROOT directory for the given image.
:param image: A pathlib.Path instance pointing to a file inside the GALLERY_ROOT directory.
"""
if image.exists():
thumb_path = Path(str(image).replace(str(settings.GALLERY_ROOT), str(settings.THUMBNAILS_ROOT)))
thumb_path.parent.mkdir(parents = True, exist_ok = True)
if not thumb_path.exists():
2023-07-30 19:11:22 -04:00
try:
with Image.open(str(image)) as pilimg:
pilimg.thumbnail(THUMB_SIZE)
pilimg.save(str(thumb_path))
2025-01-15 15:14:40 -04:00
except Exception:
2023-07-30 19:11:22 -04:00
pass