📅  最后修改于: 2023-12-03 15:04:08.360000             🧑  作者: Mango
Resizing images is a common task in image processing. However, it is important to maintain the aspect ratio of the original image when resizing. In this tutorial, we'll show you how to resize images while keeping their aspect ratio using Python.
Before we start, we need to install the required libraries. We'll be using Pillow - the Python Imaging Library fork (PIL). You can install it by running the following command:
pip install Pillow
To resize an image while keeping its aspect ratio, we'll need to calculate the new dimensions of the image that preserve the aspect ratio. We can do this by scaling the dimensions by the same factor.
Here's the code to resize an image while keeping its aspect ratio:
from PIL import Image
def resize_image_keep_aspect_ratio(image_path, output_path, max_size):
with Image.open(image_path) as image:
width, height = image.size
if max_size < width or max_size < height:
if width > height:
new_width = max_size
new_height = int(height / (width / max_size))
else:
new_height = max_size
new_width = int(width / (height / max_size))
else:
new_width = width
new_height = height
resized_image = image.resize((new_width, new_height))
resized_image.save(output_path)
Let's understand how this code works.
Image.open
function from the Pillow library.image.size
attribute.max_size
.width
or height
is greater than max_size
, we calculate the new width and height to preserve the aspect ratio of the image.width
and height
are less than or equal to max_size
, we simply keep the original width and height.image.resize
function to resize the image using the new dimensions.output_path
.Now that we have our function ready, let's see how we can use it.
resize_image_keep_aspect_ratio('path/to/input-image.jpg', 'path/to/output-image.jpg', 800)
This code will resize the input image to a maximum size of 800 pixels (either width or height, whichever is larger), while keeping its aspect ratio. The resized image will be saved to 'path/to/output-image.jpg'
.
In this tutorial, we learned how to resize an image while keeping its aspect ratio using Python. We used the Pillow library to open and resize the image and calculated the new dimensions to preserve its aspect ratio.