how to resize an image using python
Published on Aug. 22, 2023, 12:15 p.m.
To resize an image using Python, you can use the Pillow library. Here’s an example code snippet that resizes an image to a new width of 500 pixels while keeping the aspect ratio:
from PIL import Image
# Open the image file
image = Image.open('my_image.jpg')
# Get the aspect ratio of the original image
aspect_ratio = image.width / image.height
# Calculate the new height based on the new width and aspect ratio
new_width = 500
new_height = int(new_width / aspect_ratio)
# Resize the image
new_image = image.resize((new_width, new_height))
# Save the resized image
new_image.save('my_resized_image.jpg')
In this code, PIL.Image.open()
is used to open the input image, image.width
and image.height
are used to get the original image’s dimensions, and image.resize()
is used to resize the image to the desired size. Finally, new_image.save()
is used to save the resized image to a new file.
Note that Pillow provides several different resizing methods, which you can specify by passing an optional resample
parameter to image.resize()
. The default method is Image.BICUBIC
.