Python - How to resize an image

By xngo on June 12, 2019

Overview

The Python Imaging Library(PIL) is one of the core libraries for manipulating image in Python. Unfortunately, its development has stagnated since 2009. Luckily, there is an actively-developed fork of PIL called Pillow. This tutorial will use Pillow to resize image.

Installation

pip install Pillow

Resize image

#!/usr/bin/python3
 
from PIL import Image
 
# Set your resize size.
size = (128, 128)
 
try:
    im = Image.open("wildlife.jpg")
    im.thumbnail(size) # thumbnail() will preserve the aspect ratio of the original image.
    im.save("wildlife-thumbnail.jpg", "JPEG")
except IOError:
    print("Cannot resize image.")

Output

Original image Original size image

Resized image Resized image

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.