Python/Pillow:缩放子图像,但保持父图像尺寸

Python/Pillow: scale child image, but maintain parent image dimensions

我已经能够使用 .thumbnail 来缩放整个图像,但我想要缩放图像,并保留原始尺寸,如下面的第二个转换所示:

正如@Daniel 所说,您可以使用 .thumbnail() 创建缩略图,创建与原始图像大小相同的新图像,然后将缩略图粘贴到新图像中:

def scale_image(img, factor, bgcolor):
    # create new image with same mode and size as the original image
    out = PIL.Image.new(img.mode, img.size, bgcolor)
    # determine the thumbnail size
    tw = int(img.width * factor)
    th = int(img.height * factor)
    # determine the position
    x = (img.width - tw) // 2
    y = (img.height - th) // 2
    # create the thumbnail image and paste into new image
    img.thumbnail((tw,th))
    out.paste(img, (x,y))
    return out

factor应该在0到1之间,bgcolor是新图片的背景色。

示例:

img = PIL.Image.open('image.jpg')
new_img = scale_image(img, 0.5, 'white')
new_img.show()