Initial commit: simpleblog
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"""Thumbnail generation for uploaded photos (Pillow).
|
||||
|
||||
Uploads are stored at full size; galleries and admin lists ask for hundreds of
|
||||
them at once, so each upload also gets a downscaled copy next to the original.
|
||||
Thumbnails are best-effort: an unsupported/corrupt image simply has no
|
||||
thumbnail and the UI falls back to the full-size URL.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
THUMB_MAX_PX = 640
|
||||
THUMB_QUALITY = 82
|
||||
# GIF is deliberately absent: Pillow would flatten an animation to one frame.
|
||||
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
|
||||
|
||||
|
||||
def thumbnail_name(filename):
|
||||
"""Return the thumbnail filename for `filename` (same stem, _thumb suffix)."""
|
||||
stem, ext = os.path.splitext(filename)
|
||||
ext = ext.lower()
|
||||
if ext in (".jpg", ".jpeg"):
|
||||
ext = ".jpg"
|
||||
return "%s_thumb%s" % (stem, ext)
|
||||
|
||||
|
||||
def make_thumbnail(path, max_px=THUMB_MAX_PX):
|
||||
"""Write a downscaled copy next to `path`; return its filename.
|
||||
|
||||
Returns "" when the image type is unsupported or the file can't be read,
|
||||
so callers can store an empty thumb_url and fall back to the original.
|
||||
"""
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
if ext not in SUPPORTED_EXTENSIONS:
|
||||
return ""
|
||||
out_name = thumbnail_name(os.path.basename(path))
|
||||
out_path = os.path.join(os.path.dirname(path), out_name)
|
||||
try:
|
||||
with Image.open(path) as img:
|
||||
# Honour EXIF orientation so portrait phone photos aren't sideways.
|
||||
img = ImageOps.exif_transpose(img)
|
||||
img.thumbnail((max_px, max_px), Image.LANCZOS)
|
||||
if ext in (".jpg", ".jpeg"):
|
||||
img.convert("RGB").save(
|
||||
out_path, "JPEG", quality=THUMB_QUALITY, optimize=True
|
||||
)
|
||||
elif ext == ".webp":
|
||||
img.save(out_path, "WEBP", quality=THUMB_QUALITY, method=4)
|
||||
else:
|
||||
img.save(out_path, "PNG", optimize=True)
|
||||
return out_name
|
||||
except Exception:
|
||||
log.warning("thumbnail generation failed for %s", path, exc_info=True)
|
||||
try:
|
||||
os.remove(out_path)
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
Reference in New Issue
Block a user