有没有办法让 PIL 缩略图只固定一个维度和纵横比?

Is there a way to make PIL thumbnail fixed only one dimension and aspect ratio?

我有两张图像,分别为 339 x 1000 像素和 6000 x 4000 像素,我想让它们都具有 256 像素宽度, 并保持比例(纵横比)。

但是来自 PIL 库的命令:

img.thumbnail((256, 256))

使它们完全相同:

  1. 256x87 像素
  2. 171x256 像素

我不能只传递一个参数。如何仅设置自定义 width 并使其缩略图具有纵横比?

我猜功能行为是当比率 >1 时它设置正确的高度,当 <1 时则设置正确的宽度。

您可以计算正确宽度所需的缩减系数并将其应用于高度:

from PIL import Image

# Create some representative images
tall = Image.new("L",(339,1000))
wide = Image.new("L",(6000,4000))

tall_s = tall.resize((256,tall.height*256//tall.width))
wide_s = wide.resize((256,wide.height*256//wide.width))

结果是:

tall_s <PIL.Image.Image image mode=L size=256x755 at 0x7FE2F1369D30>

wide_s <PIL.Image.Image image mode=L size=256x170 at 0x7FE3003F9370>