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

时间:2016-11-17 08:18:43

标签: python pillow

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

enter image description here

1 个答案:

答案 0 :(得分:1)

正如@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()
相关问题