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