Skip to content

Instantly share code, notes, and snippets.

@aarongundel
Last active May 21, 2025 03:19
Show Gist options
  • Save aarongundel/bf93bb4ec34a7ed70cb7dc0d8f62f53f to your computer and use it in GitHub Desktop.
Save aarongundel/bf93bb4ec34a7ed70cb7dc0d8f62f53f to your computer and use it in GitHub Desktop.
Arches Simple Thumbnailer
from PIL import Image
import filetype
class SimpleThumbnailer(ThumbnailGenerator):
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
"""
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
@ydrea
Copy link

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

@aarongundel
Copy link
Author

@ydrea I'm happy to update this to something that you've actually tested! Thanks! Is there a warranty on these changes? 😄

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