Django image resizing and convert before upload

后端 未结 8 1225
余生分开走
余生分开走 2020-12-07 19:15

I searched a lot on this subject but couldn\'t really find what I need. I\'ll explain my problem :

On my website, the user can upload an image. I need to resize this

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 20:10

    from django.db import models
    from django.contrib.auth.models import User
    from PIL import Image
    
    
    
    class profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        bio = models.CharField(max_length=300)
        location = models.CharField(max_length=99)
        image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    
        def save(self):
            super().save()  # saving image first
    
            img = Image.open(self.image.path) # Open image using self
    
            if img.height > 300 or img.width > 300:
                new_img = (300, 300)
                img.thumbnail(new_img)
                img.save(self.image.path)  # saving image at the same path
    

    This example shows how to upload image after image re-sizing. Change the pixel of new_img, whatever you want.

提交回复
热议问题