Image resizing with django?

前端 未结 12 1505
温柔的废话
温柔的废话 2020-12-23 18:06

I\'m new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people\'s apps. I\'m having trouble understanding whe

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 18:58

    you can change photo size after save the data using 'Pillow' , for example i am going to change the user profile image to 300 x 300 :

    1-first make sure 'Pillow' is installed .

    2- here is my code :

    from PIL import Image
    
    class Profile(models.Model):
        user_group_rule_options = [
            ('site_manager', 'site_manager'),
            ('site_sales', 'site_sales'),
            ('site_technical_support', 'site_technical_support'),
            ('site_user', 'site_user'),
        ]
    
        PRF_user = models.OneToOneField(User, on_delete=models.CASCADE)
        PRF_user_group = models.CharField(max_length=30, choices=user_group_rule_options, default='site_user')
        PRF_image = models.ImageField(upload_to='profile_img', blank=True, null=True)
        PRF_country = CountryField()
        PRF_address = models.CharField(max_length=100)
        PRF_join_date = models.DateTimeField(auto_now_add=True)
        PRF_slug = models.SlugField(blank=True, null=True)
    
    
    
        def save(self , *args , **kwargs):
            # change profile image size
            img = Image.open(self.PRF_image.path)
            if img.width > 300 or img.height > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.PRF_image.path)
    

提交回复
热议问题