Resizing Images with Aspect Ratio Preservation Using PIL
When generating thumbnails or rescaling images, maintaining the aspect ratio is crucial to preserve image fidelity. PIL provides a straightforward method to achieve this while dynamically adjusting the width and height dimensions.
To resize an image with PIL while preserving its aspect ratio, follow these steps:
For convenience, PIL offers a method specifically designed for resizing images while maintaining their aspect ratio: Image.thumbnail. Here's an example from the PIL documentation, showcasing the use of Image.thumbnail to create thumbnails:
import os, sys import Image size = 128, 128 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 "cannot create thumbnail for '%s'" % infile
This example demonstrates how to use Image.thumbnail to create thumbnails from a list of input images, maintaining their aspect ratio while ensuring the final size is within the specified dimensions.
The above is the detailed content of How Can PIL Be Used to Resize Images While Preserving Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!