How to Resize an Image in Python

The PIL library can be used to resize an image in Python.

In this short guide, you’ll see the full steps to resize your image.

Steps to Resize an Image in Python

(1) To start, install the PIL library using the following command:

pip install Pillow

(2) Use the script below to resize your image.

Make sure to specify the source and target paths of your image file. Pay special attention to the image file extension. Here, the file extension is png (for JPEG files, use the file extension of jpg):

from PIL import Image

# Specify the source and target paths, and the desired size
source_path = r"path_to_source_image\file_name.png"
target_path = r"path_of_target_image\file_name.png"
desired_size = (1280, 720)  # Width x Height

# Open the image file
image = Image.open(source_path)
    
# Resize the image
resized_image = image.resize(desired_size)
    
# Save the resized image
resized_image.save(target_path)

(3) Optionally, you may use the following function to resize your image:

from PIL import Image

def resize_image(source_image_path, target_image_path, size):
    # Open the image file
    image = Image.open(source_image_path)
    
    # Resize the image
    resized_image = image.resize(size)
    
    # Save the resized image
    resized_image.save(target_image_path)

# Specify the source and target paths, and the desired size
source_path = r"path_to_source_image\file_name.png"
target_path = r"path_of_target_image\file_name.png"
desired_size = (1280, 720)  # Width x Height

# Resize the image
resize_image(source_path, target_path, desired_size)