How do I resize an image using PIL and maintain its aspect ratio?
To maintain aspect ratio when resizing an image with Pillow, compute the proportional height: new_height = int(original_height * (new_width / original_width))
. Use resize()
to apply this:
This keeps the aspect ratio intact, with 300
as the new width; you can replace it with your desired width.
Simplifying with thumbnail()
Automating aspect ratio maintenance
Try the Image.thumbnail()
function that automates aspect ratio maintenance:
Focusing on width or height
Main characters should always be in focus, right? If you want to prioritize width or height, use this:
Overwriting the original filename
If you're a brave programmer who doesn't fear overwriting originals, do it this way:
Mastering the edge situations
Resizing larger images
When resizing a powerful giants like 4K
images into a 128x128
dwarfs, consider a two-step resize to keep details.
Prioritizing quality
Love quality? Choose the resampling method wisely from the available options:
Image.NEAREST
is the Usain Bolt of resampling methods, but don't expect a van Gogh masterpiece.Image.LANCZOS
, the Benedict Cumberbatch of resampling, gives a balance between quality and performance.- Once upon a time,
Image.ANTIALIAS
was high quality. NowImage.Resampling.LANCZOS
is the new hot thing.
The magic of format change
Bored of one format? Change it using:
Visualization
Resizing is akin to sizing a picture into a new frame while not cropping:
Give your picture a new, snugly fitting size:
Now the artwork maintains the original proportions inside the new frames:
Art isn't supposed to stretch or squash, is it?
Taking care of all orientations and aspect ratios
Portrait, landscape or just square
Not all pictures come with the same orientation, right? Be aware!
When the aspect ratio looks weird
Sometimes the pictures are too wide or tall. Be careful with extreme size changes!
Remember the memory!
When processing multiple images, memory can start grumbling.
After saving the resized image, if you prefer peace and quiet over an angry memory, free resources using the img.close()
method!
Check the References section if you ever panic. Remember that practice makes perfect! Vote if you find this helpful + it might help me afford a coffee. No pressure though. Happy coding!👩💻
Was this article helpful?