Resizing an image

To resize an image in Pillow, the resize() method is used. This method takes two parameters – namely, new width and height.

Let’s enlarge the image. First I will print its current size:

print(img.size)

The result:

(1200, 1599)

The image is quite big. Let’s shrink it:

resized_img = img.resize((900, 500))
resized_img.show()

One drawback of using the resize() method is that it doesn’t take into consideration the aspect ratio of the image, so resized images might look stretched or squished, as is the case in our example.

The double parentheses in the line above are not an error – the size parameter is a 2-element tuple.

 

To resize an image and keep its aspect ratio, the thumbnail() method can be used. This method also takes two parameters that indicate the maximum width and height of the thumbnail:

img = Image.open('handsome.jpg')
print(img.size)
img.thumbnail((900, 500))
print(img.size)

The output:

(1200, 1599)
(375, 500)

As you can see from the image above, the aspect ratio of the original image has been kept, and the image has been resized to 375×500.

Geek University 2022