如何使用 PIL 调整图像大小并保持其纵横比? [英] How do I resize an image using PIL and maintain its aspect ratio?

查看:46
本文介绍了如何使用 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

这篇关于如何使用 PIL 调整图像大小并保持其纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆