📜  python resize image keep aspect ratio - Python (1)

📅  最后修改于: 2023-12-03 15:04:08.360000             🧑  作者: Mango

Python Resize Image and Keep Aspect Ratio

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.

Install Required Libraries

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
Resizing Images with Aspect Ratio

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.

  1. We first open the image using the Image.open function from the Pillow library.
  2. We get the original width and height of the image using the image.size attribute.
  3. We check if either the width or height is greater than max_size.
  4. If either width or height is greater than max_size, we calculate the new width and height to preserve the aspect ratio of the image.
  5. If both width and height are less than or equal to max_size, we simply keep the original width and height.
  6. We then call image.resize function to resize the image using the new dimensions.
  7. Finally, we save the resized image to the file specified by output_path.
Usage

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'.

Conclusion

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.