Yes, to resize an image using PIL without changing its aspect ratio, you can use the thumbnail() function. This function modifies the image to contain a version that fits within the specified size, maintaining the original aspect ratio.
Here’s an example:
from PIL import Image
def resize_image(input_image_path, output_image_path, size):
with Image.open(input_image_path) as img:
w, h = img.size
if w > h:
new_h = int(h * size / w)
new_w = size
else:
new_w = int(w * size / h)
new_h = size
img.thumbnail((new_w, new_h))
img.save(output_image_path)
resize_image('input.jpg', 'output.jpg', 800)
In this code, we first open the image and get its width (w) and height (h). We then calculate the new dimensions such that the aspect ratio is maintained. The thumbnail() function resizes the image so it fits within the given dimensions, reducing either the width or height depending on the aspect ratio. Finally, the resized image is saved to the specified path.