减小图像的宽度/高度以适应给定的纵横比。如何?-巨蟒图像缩略图

人气:362 发布:2022-10-16 标签: image python resize aspect-ratio thumbnails

问题描述

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

我想不出一个办法来做这件事。有什么想法吗?

推荐答案

您只需比较纵横比--根据哪个更大,这将告诉您是剪掉侧面还是顶部和底部。例如:

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

388