Categories
Python Answers

How to resize an image using PIL and maintain its aspect ratio with Python?

Spread the love

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 use the resize method.

For instance, we write

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = basewidth / float(img.size[0])
hsize = int(float(img.size[1]) * float(wpercent))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('somepic.jpg')

to open the image at the given path with Image.open.

Then we calculate the proportion to scale the image by with

basewidth / float(img.size[0])

Next we calculate the new height with

int(float(img.size[1]) * float(wpercent))

Then we call img.resize with the new dimensions and assign the returned image object back to img.

And then we call save to save the resized image.

Conclusion

To resize an image using PIL and maintain its aspect ratio with Python, we can use the resize method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *