Why don't PIL thumbnails change correctly?

I am trying to create and save a small image while saving the original user image in the model userProfilein my project, below is my code:

def save(self, *args, **kwargs):
    super(UserProfile, self).save(*args, **kwargs)
    THUMB_SIZE = 45, 45
    image = Image.open(join(MEDIA_ROOT, self.headshot.name))

    fn, ext = os.path.splitext(self.headshot.name)
    image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)        
    thumb_fn = fn + '-thumb' + ext
    tf = NamedTemporaryFile()
    image.save(tf.name, 'JPEG')
    self.headshot_thumb.save(thumb_fn, File(open(tf.name)), save=False)
    tf.close()

    super(UserProfile, self).save(*args, **kwargs)

Everything is working fine, only one thing.

The problem is that the thumbnail function only sets the width to 45and does not change the aspect ratio of the image, so I get the image 45*35for the one I'm testing on (short image).

Can someone tell me what I am doing wrong? How to make the aspect ratio I want?

PS: I tried all the methods for size: tupal: THUMB_SIZE = (45, 45)and also entered the dimensions directly into the thumbnail function.

: PIL? ?

+5
2

image.thumbnail() .

image.resize() .

UPDATE

image = image.resize(THUMB_SIZE, Image.ANTIALIAS)        
thumb_fn = fn + '-thumb' + ext
tf = NamedTemporaryFile()
image.save(tf.name, 'JPEG')
+12

:

import Image # Python Imaging Library
THUMB_SIZE= 45, 45
image # your input image

45 × 45, :

new_image= image.resize(THUMB_SIZE, Image.ANTIALIAS)

, 45 × 45, , :

new_image= Image.new(image.mode, THUMB_SIZE)
image.thumbnail(THUMB_SIZE, Image.ANTIALIAS) # in-place
x_offset= (new_image.size[0] - image.size[0]) // 2
y_offset= (new_image.size[1] - image.size[1]) // 2
new_image.paste(image, (x_offset, y_offset))
+4

All Articles