Home >Backend Development >Python Tutorial >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:
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!