Home >Backend Development >Python Tutorial >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:
Calculate the resize ratio:
ratio = min(max_width / width, max_height / height)
The new image size becomes:
new_size = old_size * ratio
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!