Sometimes, we want to resize an image using PIL and maintain its aspect ratio with Python.
In this article, we’ll look at how to resize an image using PIL and maintain its aspect ratio with Python.
How to resize an image using PIL and maintain its aspect ratio with Python?
To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open
.
Then we calculate the new width and height to scale the image to according to the new width.
And then we resize the image with the resize
method and save the new image with the save
method.
For instance, we write:
from PIL import Image
basewidth = 300
img = Image.open('test1.png')
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('somepic.png')
We set the new width with:
basewidth = 300
Then we open the image with:
img = Image.open('test1.png')
Next, we compute the scale factor with:
wpercent = (basewidth / float(img.size[0]))
Then we get the height of the image with:
hsize = int((float(img.size[1]) * float(wpercent)))
Next, we write:
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
to resize the image.
We use Image.ANTIALIAS
to apply image anti-aliasing while resizing.
And finally, we call image.save
with the file path to save to to save the resized image.
Conclusion
To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open
.
Then we calculate the new width and height to scale the image to according to the new width.
And then we resize the image with the resize
method and save the new image with the save
method.
2 replies on “How to resize an image using PIL and maintain its aspect ratio with Python?”
Very interesting. Can you make it where the you have a baseheight instead of a basewidth, and adjust the width based on the baseheight?
Yes. You can set a fixed height and calculate the width from the height and aspect ratio.