3
import Image

image  = Image.open('images/original.jpg')
width  = image.size[0]
height = image.size[1]

if width > height:
    difference = width - height
    offset     = difference / 2
    resize     = (offset, 0, width - offset, height)

else:
    difference = height - width
    offset     = difference / 2
    resize     = (0, offset, width, height - offset)

thumb = image.crop(resize).resize((200, 200), Image.ANTIALIAS)
thumb.save('thumb.jpg')

这是我当前的缩略图生成脚本。它的工作方式是:

如果您有一个 400x300 的图像,并且您想要一个 100x100 的缩略图,那么原始图像的左侧和右侧将需要 50 个像素。因此,将其大小调整为 300x300。这使原始图像具有与新缩略图相同的纵横比。之后,它将缩小到所需的缩略图大小。

这样做的好处是:

  • 缩略图取自图像的中心
  • 纵横比不会搞砸

如果您将 400x300 图像缩小到 100x100,它看起来会被压扁。如果您从 0x0 坐标获取缩略图,您将获得图像的左上角。通常,图像的焦点是中心。

我想要做的是给脚本一个任意纵横比的宽度/高度。例如,如果我想将 400x300 的图像调整为 400x100,它应该从图像的左侧和右侧剃掉 150px...

我想不出办法来做到这一点。有任何想法吗?

4

1 回答 1

26

您只需要比较纵横比 - 取决于哪个更大,它会告诉您是切掉侧面还是顶部和底部。例如怎么样:

import Image

image  = Image.open('images/original.jpg')
width  = image.size[0]
height = image.size[1]

aspect = width / float(height)

ideal_width = 200
ideal_height = 200

ideal_aspect = ideal_width / float(ideal_height)

if aspect > ideal_aspect:
    # Then crop the left and right edges:
    new_width = int(ideal_aspect * height)
    offset = (width - new_width) / 2
    resize = (offset, 0, width - offset, height)
else:
    # ... crop the top and bottom:
    new_height = int(width / ideal_aspect)
    offset = (height - new_height) / 2
    resize = (0, offset, width, height - offset)

thumb = image.crop(resize).resize((ideal_width, ideal_height), Image.ANTIALIAS)
thumb.save('thumb.jpg')
于 2011-01-20T07:50:12.423 回答