Home >Backend Development >Python Tutorial >How Can I Resize an Image While Preserving its Aspect Ratio Using PIL?

How Can I Resize an Image While Preserving its Aspect Ratio Using PIL?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 19:57:11660browse

How Can I Resize an Image While Preserving its Aspect Ratio Using PIL?

Resizing Images with Aspect Ratio Preservation Using PIL

Maintaining an image's aspect ratio during resizing is crucial for preserving its visual integrity. The Python Imaging Library (PIL) offers a convenient solution for this task.

Problem:

"Can I resize an image while maintaining its aspect ratio?"

Answer:

  1. Define a maximum desired size (width and height).
  2. Calculate the resize ratio:

    ratio = min(max_width / width, max_height / height)
  3. The new image size becomes:

    new_size = old_size * ratio
  4. For convenience, PIL provides the Image.thumbnail() method:
from PIL import Image

size = 128, 128
im = Image.open("image.jpg")
im.thumbnail(size, Image.Resampling.LANCZOS)
im.save("image.thumbnail.jpg", "JPEG")

In this example, the image is resized to a maximum width and height of 128 pixels, while preserving its original aspect ratio. The Image.Resampling.LANCZOS option provides high-quality resampling.

The above is the detailed content of How Can I Resize an Image While Preserving its Aspect Ratio Using PIL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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