Resize Image keeping aspect ratio – Python PIL Image Module

Below Python code resizes an image keeping it’s aspect ratio using PIL library Image Module.

from PIL import Image

im = Image.open("image.jpg")
height = 900
wpercent = (height/float(im.size[1]))
width = int(im.size[0]*float(wpercent))
resized = im.resize((width, height), Image.ANTIALIAS)
resized.show()

The above code is tested on Windows 10 PC using PyCharm 2019.3.3

In the code, we have set the height of the image to 900

height = 900

Percentage of height of the resized image calculation

wpercent = (height/float(im.size[1]))

proportional width value calculation using below formula

width = int(im.size[0]*float(wpercent))

resize() method resizes the image

resized = im.resize((width, height), Image.ANTIALIAS)

show() method displays the resized image with default photo viewer on your PC

resized.show()

Also see: Python Pillow (PIL) Tutorial – With Examples

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published.