Last modified: Oct 19, 2024 By Alexander Williams

Resizing Images Using Python Pillow

The Pillow library is a powerful tool for image processing in Python. In this article, we'll explore how to resize images easily. Whether you're working on a personal project or a professional application, resizing images is a common requirement.

Getting Started with Pillow

Before we dive into resizing images, make sure you have Pillow installed. If you haven't installed it yet, refer to our article on Pillow: Installation and getting started (Python).

Loading an Image

First, you need to load the image you want to resize. You can do this using the Image.open() method:


from PIL import Image

# Load an image
image = Image.open('path_to_your_image.jpg')

Resizing the Image

To resize the image, use the resize() method. You can specify the new size as a tuple (width, height):


# Resize the image
new_size = (800, 600)
resized_image = image.resize(new_size)

The above code resizes the image to a width of 800 pixels and a height of 600 pixels. Adjust the new_size tuple according to your needs.

Maintaining Aspect Ratio

It's important to maintain the aspect ratio when resizing images to avoid distortion. You can do this by calculating the new dimensions based on the original aspect ratio:


original_size = image.size
aspect_ratio = original_size[0] / original_size[1]
new_width = 800
new_height = int(new_width / aspect_ratio)

# Resize while maintaining aspect ratio
resized_image = image.resize((new_width, new_height))

Saving the Resized Image

After resizing, you can save the new image using the save() method:


# Save the resized image
resized_image.save('resized_image.jpg')

Conclusion

Resizing images with Pillow is straightforward and effective. You can load, resize, and save images easily using the methods described above. For more details on how to manipulate images, check out our articles on Python-Pillow: How to get Image Filename, Size, Format, and Mode and Python-Pillow: How to Show an image in Python.