user1658296 user1658296 - 1 year ago 84
Python Question

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

I have been able to use .thumbnail to scale the entire image, but I'd to scale the image, and preserve the original dimensions as depicted in the second transformation below:

enter image description here

Answer Source

As @Daniel said, you can create the thumbnail image using .thumbnail(), create an new image with same size of the original image and then paste the thumbnail into the new image:

def scale_image(img, factor, bgcolor):
    # create new image with same mode and size as the original image
    out =, 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
    out.paste(img, (x,y))
    return out

factor should be between 0 and 1, and bgcolor is the background color of the new image.


img ='image.jpg')
new_img = scale_image(img, 0.5, 'white')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download