Ere*_*rez 5 python django django-models python-imaging-library
我userProfile在项目模型中保存原始用户图像时尝试创建并保存缩略图,下面是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
一切都运转正常,只有这一件事.
问题是缩略图功能仅将宽度设置为45并且不会改变图像的比率方面,因此我得到的45*35是我正在测试的图像(短图像).
谁能告诉我我做错了什么?如何强制我想要的宽高比?
PS:我已经尝试了所有大小的方法:tupal: THUMB_SIZE = (45, 45)并且还直接输入尺寸到缩略图功能.
另一个问题:PIL中调整大小和缩略图功能之间的差异是什么?何时使用调整大小以及何时使用缩略图?
BFi*_*Fil 12
所述image.thumbnail()函数将保持原始图像的高宽比.
请改用image.resize().
UPDATE
image = image.resize(THUMB_SIZE, Image.ANTIALIAS)
thumb_fn = fn + '-thumb' + ext
tf = NamedTemporaryFile()
image.save(tf.name, 'JPEG')
Run Code Online (Sandbox Code Playgroud)
鉴于:
\n\nimport Image # Python Imaging Library\nTHUMB_SIZE= 45, 45\nimage # your input image\nRun Code Online (Sandbox Code Playgroud)\n\n如果您想将任何图像的大小调整为 45\xc3\x9745,您应该使用:
\n\nnew_image= image.resize(THUMB_SIZE, Image.ANTIALIAS)\nRun Code Online (Sandbox Code Playgroud)\n\n但是,如果您想要大小为 45\xc3\x9745 的结果图像,同时调整输入图像的大小,保持其纵横比并用黑色填充缺失的像素:
\n\nnew_image= Image.new(image.mode, THUMB_SIZE)\nimage.thumbnail(THUMB_SIZE, Image.ANTIALIAS) # in-place\nx_offset= (new_image.size[0] - image.size[0]) // 2\ny_offset= (new_image.size[1] - image.size[1]) // 2\nnew_image.paste(image, (x_offset, y_offset))\nRun Code Online (Sandbox Code Playgroud)\n