To resize an image in Python using the PIL (Python Imaging Library) library, you can follow the code snippet provided below:
from PIL import Image
def resize_image(input_image_path, output_image_path, new_width, new_height):
"""
Resize an image using PIL.
:param input_image_path: The path to the input image.
:param output_image_path: The path to save the resized image.
:param new_width: The desired width of the resized image.
:param new_height: The desired height of the resized image.
"""
with Image.open(input_image_path) as image:
resized_image = image.resize((new_width, new_height))
resized_image.save(output_image_path)
# Example usage:
input_path = 'input_image.jpg'
output_path = 'resized_image.jpg'
new_width = 800
new_height = 600
resize_image(input_path, output_path, new_width, new_height)
In this example, we define the resize_image
function that takes four parameters: input_image_path
(the path to the input image), output_image_path
(the path where the resized image will be saved), new_width
(the desired width of the resized image), and new_height
(the desired height of the resized image).
Within the function, we use the Image.open
method from PIL to open the input image. Then, we call the resize
method on the image object, passing a tuple of (new_width, new_height)
as the new size. Finally, we save the resized image using the save
method.
You can replace 'input_image.jpg'
, 'resized_image.jpg'
, 800
, and 600
with your own file paths and desired width and height values.
Make sure you have the PIL 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.
+ There are no comments
Add yours