Django / PIL - save thumbnail version right when image is uploaded

前端 未结 6 819
挽巷
挽巷 2021-01-30 09:39

This is my forms.py:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserImages
        fields = [\'photo\']

and this i

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 10:20

    Based on xjtian's answer. This works for Python 3:

    import os.path
    from PIL import Image
    from io import BytesIO
    from django.core.files.base import ContentFile
    from .my_app_settings import THUMB_SIZE    
    
    class Photo(models.Model):
        photo = models.ImageField(upload_to='photos')
        thumbnail = models.ImageField(upload_to='thumbs', editable=False)
    
        def save(self, *args, **kwargs):
    
            if not self.make_thumbnail():
                # set to a default thumbnail
                raise Exception('Could not create thumbnail - is the file type valid?')
    
            super(Photo, self).save(*args, **kwargs)
    
        def make_thumbnail(self):
    
            image = Image.open(self.photo)
            image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
    
            thumb_name, thumb_extension = os.path.splitext(self.photo.name)
            thumb_extension = thumb_extension.lower()
    
            thumb_filename = thumb_name + '_thumb' + thumb_extension
    
            if thumb_extension in ['.jpg', '.jpeg']:
                FTYPE = 'JPEG'
            elif thumb_extension == '.gif':
                FTYPE = 'GIF'
            elif thumb_extension == '.png':
                FTYPE = 'PNG'
            else:
                return False    # Unrecognized file type
    
            # Save thumbnail to in-memory file as StringIO
            temp_thumb = BytesIO()
            image.save(temp_thumb, FTYPE)
            temp_thumb.seek(0)
    
            # set save=False, otherwise it will run in an infinite loop
            self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=False)
            temp_thumb.close()
    
            return True
    

提交回复
热议问题