Home >Backend Development >Python Tutorial >How to Maintain Aspect Ratio When Resizing Images with PIL?

How to Maintain Aspect Ratio When Resizing Images with PIL?

DDD
DDDOriginal
2024-12-06 18:29:14531browse

How to Maintain Aspect Ratio When Resizing Images with PIL?

Preserving Aspect Ratio while Resizing Images Using PIL

In Python Imaging Library (PIL), resizing an image while maintaining its aspect ratio can be achieved through specific calculations. When creating thumbnails, it's crucial to maintain the original proportions of the image.

Solution:

  1. Define a maximum size: Determine the maximum dimensions for the resized image.
  2. Calculate resize ratio: Compute a ratio by taking the minimum of (maximum width/original width) and (maximum height/original height).
  3. Determine proper size: Multiply the original size of the image by the calculated ratio to obtain the appropriate dimensions for resizing.

For simplicity, PIL provides the Image.thumbnail method to handle resizing while preserving aspect ratio:

import os, sys
from PIL import Image

size = (128, 128) # Desired thumbnail size

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.Resampling.LANCZOS)
            im.save(outfile, "JPEG")
        except IOError:
            print(f"Cannot create thumbnail for '{infile}'")

In this script, images are resized to a thumbnail size of (128, 128) using Lanczos resampling for improved image quality.

The above is the detailed content of How to Maintain Aspect Ratio When Resizing Images with PIL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn