【问题标题】:Why does PIL thumbnail not resizing correctly?为什么 PIL 缩略图无法正确调整大小?
【发布时间】:2011-05-30 14:29:11
【问题描述】:

在我的项目中将原始用户图像保存在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)

一切正常,只有这一件事。

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

谁能告诉我我做错了什么?如何强制我想要的宽高比?

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

另一个问题:PIL 中的 resize 和 thumbnail 函数有什么区别?何时使用调整大小以及何时使用缩略图?

【问题讨论】:

    标签: python django django-models python-imaging-library


    【解决方案1】:

    给定:

    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))
    

    【讨论】:

      【解决方案2】:

      image.thumbnail() 函数将保持原始图像的纵横比。

      请改用image.resize()

      更新

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

      【讨论】:

      • 10x,但我也尝试过 image.resize(THUMB_SIZE, Image.ANTIALIAS) ,其中 THUMB_RESIZE 是一个 tupal (THUMB_RESIZE = (45,45) 并且它现在根本没有调整大小.. .这里还有什么吗?(​​这是我在链接中读到的)...谢谢:-)
      • 再次感谢ShadowCloud,我找到了问题......你的回答很好,但是resize函数返回一个需要保存的值,并且缩略图函数是无效的所以不需要保存,所以如果使用图像.resize(...) 它需要是 image = image.resize(...),花了我一些时间,但我明白了...你能在你的答案中修正它吗? :-)
      • 还有image.fit(THUMB_SIZE, Image.ANTIALIAS),它将使用给定的尺寸,但通过裁剪图像来保持纵横比。见:djangosaur.tumblr.com/post/422589280/…
      猜你喜欢
      • 2011-07-04
      • 2014-04-03
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2011-11-19
      • 2019-05-06
      • 2021-02-01
      • 2012-12-01
      相关资源
      最近更新 更多