Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.

推荐答案

Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

The proper size is oldsize*ratio.

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

Python相关问答推荐

三个给定的坐标可以是矩形的点吗

在Python中对分层父/子列表进行排序

大Pandas 胚胎中产生组合

将输入管道传输到正在运行的Python脚本中

管道冻结和管道卸载

如何在polars(pythonapi)中解构嵌套 struct ?

pyscript中的压痕问题

如果条件不满足,我如何获得掩码的第一个索引并获得None?

SQLAlchemy Like ALL ORM analog

关于Python异步编程的问题和使用await/await def关键字

如何从数据库上传数据到html?

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

使用密钥字典重新配置嵌套字典密钥名

如何在Python中找到线性依赖mod 2

如何在TensorFlow中分类多个类

在Python中从嵌套的for循环中获取插值

Flask运行时无法在Python中打印到控制台

处理Gekko的非最优解

Scipy差分进化:如何传递矩阵作为参数进行优化?

#将多条一维曲线计算成其二维数组(图像)表示