Resize an Image with PIL and Keep Aspect Ratio (Python)

This script will resize an image using PIL (Python Imaging Library)to a width of 300 pixels and a height proportional to the new width. Itdoes this by determining what percentage 300 pixels is of the originalwidth (img.size[0]) and then multiplying the original height(img.size[1]) by that percentage. Change “300″ to any other number tochange the default width of your images.

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

Tags: , , ,

Next Post:
Previous Post:

Leave a Reply