Skip to content

Instantly share code, notes, and snippets.

@ydrea
Forked from aarongundel/thumbnailer.py
Created May 21, 2025 00:30
Show Gist options
  • Save ydrea/f8814b1ecdf6133b61f13f358eda5ea0 to your computer and use it in GitHub Desktop.
Save ydrea/f8814b1ecdf6133b61f13f358eda5ea0 to your computer and use it in GitHub Desktop.
Arches Simple Thumbnailer
from PIL import Image
import filetype
class SimpleThumbnailer(ThumbnailGenerator):
IMAGES = (
'png', 'jpg', 'jpeg', 'jpe', 'gif', 'bmp', 'dib', 'dcx',
'eps', 'ps', 'im', 'pcd', 'pcx', 'pbm', 'pbm', 'ppm',
'psd', 'tif', 'tiff', 'xbm', 'xpm',
)
def make_thumbnail(self, inputfile_path, outputfile_path, **kwargs):
"""
Args:
inputfile_path: a path to a file on disk to create a thumbnail from
outputfile_path: a path to a file on disk where the thumbnail will be written to
Returns:
None
"""
file_type = filetype.guess(inputfile_path)
if file_type in IMAGES:
image = Image.open(inputfile_path)
image.thumbnail((300, 300))
image.save(outputfile_path)
@ydrea
Copy link
Author

ydrea commented May 21, 2025

I tried to use this with 'GENERATE_THUMBNAILS_ON_DEMAND = False', but it broke my gunicorn (took too much CPU time).
A first attempt of a fix is:

from PIL import Image
from django.utils.translation import gettext_lazy as _

class SimpleThumbnailer:
    # without Django dependencies, as translations were breaking it
    
    def make_thumbnail(self, inputfile_path, outputfile_path, **kwargs):
        try:
            # image extensions
            image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp')
            
            if not inputfile_path.lower().endswith(image_extensions):
                return False
                
            with Image.open(inputfile_path) as img:
                img.thumbnail((300, 300))
                if img.mode in ('RGBA', 'P'):
                    img = img.convert('RGB')
                img.save(outputfile_path)
            return True
            
        except Exception as e:
            print(_("Thumbnail generation failed: %s") % str(e))
            return False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment