2016-11-17 45 views

回答

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()