小编典典

Python-如何使用PIL调整图像大小并保持其纵横比?

python

有什么明显的方法可以实现我所缺少的吗?我只是想制作缩略图。


阅读 1765

收藏
2020-02-14

共1个答案

小编典典

定义最大尺寸。然后,通过计算调整大小比例min(maxwidth/width, maxheight/height)

适当大小oldsize*ratio

当然,还有一个库方法可以做到这一点:method Image.thumbnail
以下是PIL文档中的一个(经过编辑的)示例。

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
2020-02-14