减小图像的宽度/高度以适合给定的宽高比。怎么样? - Python图像缩略图

时间:2011-01-20 07:08:03

标签: python image resize thumbnails aspect-ratio

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

我想不出办法做到这一点。有什么想法吗?

1 个答案:

答案 0 :(得分:12)

你只需要比较纵横比 - 取决于哪个更大,它将告诉你是否切掉两侧或顶部和底部。例如怎么样:

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