如何调整图片宽高以适应特定宽高比? - Python 图片缩略图

3 投票
1 回答
13813 浏览
提问于 2025-04-16 10:17
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像素。这种做法可以保持原图和新缩略图的比例一致。接下来,它会把这个300x300的图片再缩小到100x100的尺寸。

这样做的好处是:

  • 缩略图是从图片的中心部分提取的
  • 比例不会被搞乱

如果你直接把400x300的图片缩小到100x100,它看起来会很扁。假如你从0x0的坐标开始提取缩略图,你得到的就是图片的左上角部分。通常情况下,图片的重点在于中心位置。

我想要实现的是,可以给脚本输入任何比例的宽度和高度。例如,如果我想把400x300的图片调整为400x100,它应该从图片的左右两边各剪掉150像素……

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

1 个回答

28

你只需要比较一下宽高比——根据哪个更大,就能知道是要剪掉两边还是上下的部分。比如说:

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

撰写回答