Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

generate-thumbnails-in-django-with-pil

from django.db import models
from my.images import make_thumbnail


class Image(models.Model):
    image = models.ImageField(upload_to='')
    thumbnail = models.ImageField(upload_to='', editable=False)
    icon = models.ImageField(upload_to='', editable=False)

    def save(self, *args, **kwargs):
        # save for image
        super(Image, self).save(*args, **kwargs)

        make_thumbnail(self.thumbnail, self.image, (200, 200), 'thumb')
        make_thumbnail(self.icon, self.image, (100, 100), 'icon')

        # save for thumbnail and icon
        super(Image, self).save(*args, **kwargs)
Comment

generate-thumbnails-in-django-with-pil

from django.core.files.base import ContentFile
import os.path
from PIL import Image
from io import BytesIO


def make_thumbnail(dst_image_field, src_image_field, size, name_suffix, sep='_'):
    """
    make thumbnail image and field from source image field

    @example
        thumbnail(self.thumbnail, self.image, (200, 200), 'thumb')
    """
    # create thumbnail image
    image = Image.open(src_image_field)
    image.thumbnail(size, Image.ANTIALIAS)

    # build file name for dst
    dst_path, dst_ext = os.path.splitext(src_image_field.name)
    dst_ext = dst_ext.lower()
    dst_fname = dst_path + sep + name_suffix + dst_ext

    # check extension
    if dst_ext in ['.jpg', '.jpeg']:
        filetype = 'JPEG'
    elif dst_ext == '.gif':
        filetype = 'GIF'
    elif dst_ext == '.png':
        filetype = 'PNG'
    else:
        raise RuntimeError('unrecognized file type of "%s"' % dst_ext)

    # Save thumbnail to in-memory file as StringIO
    dst_bytes = BytesIO()
    image.save(dst_bytes, filetype)
    dst_bytes.seek(0)

    # set save=False, otherwise it will run in an infinite loop
    dst_image_field.save(dst_fname, ContentFile(dst_bytes.read()), save=False)
    dst_bytes.close()
Comment

PREVIOUS NEXT
Code Example
Python :: k and M to int in pandas 
Python :: wx.SingleInstanceCheckerindexmodules 
Python :: python if boolean example 
Python :: create line in canvas widget object 
Python :: python check if more than 1 is true 
Python :: xmlrpc get all posts 
Python :: colorama input python 
Python :: get random consonant python 
Python :: python zip function 
Python :: how to check the version of ployly 
Python :: ipython list command history 
Python :: mp.solutions.findhands not in python 3.8 
Python :: numpy np sign change in df pandas zero crossing 
Python :: openpyxl iter_rows skip first 
Python :: python pipe select where 
Python :: len range 
Python :: Handling single exception 
Python :: cosine similiarity OF A VECTOR WITH OTHER VECTORS IN A MATRIX 
Python :: python remove xa0 
Python :: pandas perform action on column 
Python :: next function with inherited list python 
Python :: django froms 
Python :: pandas merge validate 
Python :: python encryption program 
Python :: inline keyboard telegram bot python 
Python :: join python 
Python :: how to find duplicates in pandas 
Python :: python how to put int into list 
Python :: how to add elements in a dictionary in python 
Python :: python list tutorial 
ADD CONTENT
Topic
Content
Source link
Name
3+2 =