Home >Backend Development >Python Tutorial >How Can I Resize Images with PIL While Maintaining Aspect Ratio?
The Python Imaging Library (PIL) offers a comprehensive set of image manipulation functions. One useful operation is resizing images, but many developers encounter challenges in maintaining the original aspect ratio. This article delves into this issue and provides solutions to ensure proportional image resizing.
While attempting to create thumbnails, a user stumbled upon the following challenge:
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
To resize an image while preserving its aspect ratio, consider the following steps:
import os, sys from PIL import Image size = 128, 128 # Define the maximum size of the thumbnail for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" # Generate the output filename if infile != outfile: try: im = Image.open(infile) im_copy = im.copy() # Create a copy to avoid modifying the original image im_copy.thumbnail(size, Image.Resampling.LANCZOS) # Resize the image im_copy.save(outfile, "JPEG") # Save the resized image except IOError: print(f"cannot create thumbnail for '{infile}'") # Handle any exceptions
The above is the detailed content of How Can I Resize Images with PIL While Maintaining Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!