Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rluts/0935d980c7c559ec93c63db9a4306103 to your computer and use it in GitHub Desktop.
Save rluts/0935d980c7c559ec93c63db9a4306103 to your computer and use it in GitHub Desktop.
Django create thumbnail form ImageField and save in a different ImageField - now with updating!
def create_thumbnail(instance, image_field, thumb_field):
# original code for this method came from
# http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/
# https://gist.github.com/valberg/2429288
# adapted to python 3
# insert this code to utils.py
# example:
# instance = Photo.objects.get(id=1)
# create_thumbnail(instance, 'photo', 'photo_thumbnail')
# example 2:
# signals.py:
# from fieldsignals import post_save_changed # https://github.com/craigds/django-fieldsignals
# @receiver(post_save_changed, sender=SeminarPhotos)
# def set_thumbnail(sender, instance, changed_fields=None, **kwargs):
# names = [i.name for i in changed_fields.keys()]
# if 'photo' in names and instance.photo:
# create_thumbnail(instance, 'photo', 'photo_thumbnail')
# If there is no image associated with this.
# do not create thumbnail
if not getattr(instance, image_field, None):
return None
# Set our max thumbnail size in a tuple (max width, max height)
thumbnail_size = (150, 150)
mime = Magic(mime=True)
django_type = mime.from_file(getattr(instance, image_field).file.name)
if django_type == 'image/jpeg':
pil_type = 'jpeg'
elif django_type == 'image/png':
pil_type = 'png'
elif django_type == 'image/x-ms-bmp':
pil_type = 'bmp'
elif django_type == 'image/gif':
pil_type = 'gif'
elif django_type == 'image/tiff':
pil_type = 'tiff'
else:
return None
image = Image.open(getattr(instance, image_field).file.name)
thumb = ImageOps.fit(image, thumbnail_size, Image.ANTIALIAS)
buffer = BytesIO()
thumb.save(buffer, pil_type)
buffer.seek(0)
suf = SimpleUploadedFile(os.path.split(getattr(instance, image_field).name)[-1],
buffer.read(), content_type=django_type)
setattr(instance, thumb_field, suf)
instance.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment