0

Currently making a basic Django project, following a well set out tutorial off youtube. All's going well and I usually try to debug issues myself and I wouldn't be asking if I was stuck.

Issue:

This code is meant to check the image size once it's reuploaded and then format to make it square but looking at the image linked, this isn't the case. Is my code wrong? is there another way to check and validate images?

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile_pics")

    def __str__(self):
        return f'{self.user.username} Profile'


    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

Reference Screenshot for Context Reference Screenshot for Context

Update:

Hi Allan, tried your solution to this and now getting errors when uploading the image back. Image of Error

thepunitsingh
  • 713
  • 1
  • 12
  • 30
Tobsterr
  • 35
  • 6
  • The linked image is 1920x1040 so it should trigger the if statement in safe(). What behavior are you observing? What you have you tried to resolve the issue? – Allan Wind Dec 26 '20 at 00:17
  • So when I attempt to upload an image that is not square, it will strech an image when displaying and not render as a square. I have tried several soultions to this but no avial. Note: The only styling I have on these images are a boostrap style "class="rounded-circle"" – Tobsterr Dec 26 '20 at 00:53
  • Your original code does not make the image square. The 2nd snippet of code that I shared below tells you how to do that. If that answers your question please mark it solved. If you need help with the front-end open a new question. – Allan Wind Dec 26 '20 at 00:57

2 Answers2

0

I extracted the minimal code of save():

from PIL import Image
img = Image.open('g8uf6.png')
output_size = (300,300)
img.thumbnail(output_size)
img.save('thumbnail.png')

and found that it creates the thumbnail.png preserve the aspect of the image of 300x162. Your link a picture of the result, not the input image, I am guessing, so it would demonstrate the same (correct) behavior. If you indeed want a square image, then scale the original first:

output_size = (300,300)  
img = Image.open(g8uf6.png').resize(output_size)

You usually want to preserve the aspect ratio especially for photos of people.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
0
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img_width = 300
img_height = 300
img = Image.open(self.image.path).resize((img_width, img_height))
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
Tobsterr
  • 35
  • 6