user1658296 user1658296 - 17 days ago 5
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

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 = 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 should be between 0 and 1, and bgcolor is the background color of the new image.

Example:

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