Resizing Images with PIL While Preserving Aspect Ratio
When creating thumbnails, it can be crucial to maintain the original aspect ratio of images. In this article, we'll explore how to achieve this using the Python Imaging Library (PIL).
Approach:
Alternative Method using PIL Library:
PIL provides the Image.thumbnail() method specifically designed for this purpose. It takes the maximum size as an argument and automatically adjusts the image size while maintaining the aspect ratio.
Here's an example from the PIL documentation:
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
The above is the detailed content of How to Resize Images with PIL While Maintaining Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!