如何使用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