How to Resize an Image in Python?

Estimated read time 2 min read

To resize an image in Python, you can use the Pillow library, which is a popular library for image processing tasks. You can install Pillow using pip by running the command pip install pillow.

Here’s an example code snippet that demonstrates how to resize an image using Pillow in Python:

from PIL import Image

def resize_image(input_image_path, output_image_path, size):
    Resize an image using Pillow.

    :param input_image_path: The path to the input image.
    :param output_image_path: The path to save the resized image.
    :param size: The desired size in pixels, as a tuple (width, height).
    with as image:
        resized_image = image.resize(size)

# Example usage:
input_path = 'input_image.jpg'
output_path = 'resized_image.jpg'
new_size = (800, 600)  # New size of the image

resize_image(input_path, output_path, new_size)

In this code, we define the resize_image function that takes three parameters: input_image_path (the path to the input image), output_image_path (the path where the resized image will be saved), and size (the desired size of the resized image in pixels, specified as a tuple of width and height).

Within the function, we use the method from Pillow to open the input image. Then, we call the resize method on the image object, passing the desired size. Finally, we save the resized image using the save method.

You can replace 'input_image.jpg', 'resized_image.jpg', and (800, 600) with your own file paths and desired size values.

Make sure you have the Pillow library installed, and the input image file exists in the specified location. The code will resize the image and save the resized version to the specified output path.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply