Resizing Images Using Python

Posted by

Resizing Images with Python

Resizing Images with Python

Resizing images is a common task in web development and data processing. With Python, you can easily resize images using the Pillow library. In this article, we will show you how to resize images with Python.

Installing Pillow

The first step is to install the Pillow library. You can do this using pip, the Python package manager. Open a terminal and type the following command:

pip install pillow

Resizing an Image

Once you have installed Pillow, you can start resizing images. First, import the necessary modules:

from PIL import Image
import os
    

Next, open the image file using the Image.open() method:

image = Image.open('input_image.jpg')
    

Now, you can resize the image using the Image.resize() method:

resized_image = image.resize((300, 200))
    

Finally, save the resized image to a new file:

resized_image.save('output_image.jpg')
    

Resizing with Aspect Ratio

If you want to maintain the aspect ratio of the image while resizing, you can use the thumbnail() method instead of resize():

image = Image.open('input_image.jpg')
image.thumbnail((300, 200))
image.save('output_image.jpg')
    

Conclusion

Resizing images with Python is simple and easy using the Pillow library. Whether you need to resize images for a website, a machine learning project, or any other application, Python provides the tools to do so efficiently. Try out these examples and start resizing images with Python today!