为什么PIL缩略图无法正确调整大小? [英] Why does PIL thumbnail not resizing correctly?

查看:87
本文介绍了为什么PIL缩略图无法正确调整大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将原始用户图像保存到项目中的userProfile模型中时,我试图创建并保存缩略图图像,以下是我的代码:

I am trying to create and save a thumbnail image when saving the original user image in the userProfile model in 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)

一切正常,就这一件事.

Every thing is working OK, just this one thing.

问题是缩略图功能仅将宽度设置为45,并且不会更改图像的比例,因此对于正在测试的图像,我得到的是45*35的图像(短图像).

The problem is that the thumbnail function only sets the width to 45 and doesn't change the ratio aspect of the image so I am getting an image of 45*35 for the one that I am testing on (short image).

有人可以告诉我我在做什么错吗?如何强制我想要长宽比?

Can any one tell me what am I doing wrong? How to force the aspect ratio I want?

P.S .:我已经尝试了所有尺寸设置方法:tupal: THUMB_SIZE = (45, 45),并将尺寸直接输入缩略图功能.

P.S.: I've tried all the methods for size: tupal: THUMB_SIZE = (45, 45) and entering the sizes directly to the thumbnail function also.

另一个问题:PIL中的调整大小和缩略图功能之间的区别是什么?何时使用调整大小以及何时使用缩略图?

Another question: what is the deference between resize and thumbnail functions in PIL? When to use resize and when to use thumbnail?

推荐答案

image.thumbnail() 函数将保持原始图像的长宽比.

The image.thumbnail() function will maintain the aspect ratio of the original image.

使用 image.resize() 代替.

更新

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

这篇关于为什么PIL缩略图无法正确调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆