如何使用 PIL 调整图像大小并保持其纵横比?
问题描述:
是否有明显的方法可以做到这一点,但我缺少这种方法?我只是想制作缩略图.
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
答
定义最大尺寸.然后,通过取min(maxwidth/width, maxheight/height)
来计算调整大小比例.
Define a maximum size.
Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height)
.
合适的尺寸是oldsize*ratio
.
当然还有一个库方法可以做到这一点:方法Image.thumbnail
.
下面是 PIL 文档 中的(经过编辑的)示例.
There is of course also a library method to do this: the method Image.thumbnail
.
Below is an (edited) example from the PIL documentation.
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile