Home > Backend Development > Python Tutorial > How to Resize Images with PIL While Maintaining Aspect Ratio?

How to Resize Images with PIL While Maintaining Aspect Ratio?

Susan Sarandon
Release: 2024-12-11 08:26:09
Original
823 people have browsed it

How to Resize Images with PIL While Maintaining Aspect Ratio?

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:

  1. Define Maximum Size: Determine the desired maximum width and height for your thumbnails.
  2. Compute Resize Ratio: Calculate the minimum scaling ratio by finding the smaller of the ratios maxwidth/width and maxheight/height.
  3. Calculate New Size: Multiply the original size by the computed ratio to obtain the proper size for the thumbnail.

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template