How do I resize an image using PIL and maintain its aspect ratio? How do I resize an image using PIL and maintain its aspect ratio? python python

How do I resize an image using PIL and maintain its aspect ratio?


Define a maximum size.Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

The proper size is oldsize*ratio.

There is of course also a library method to do this: the method Image.thumbnail.
Below is an (edited) example from the PIL documentation.

import os, sysimport Imagesize = 128, 128for infile in sys.argv[1:]:    outfile = os.path.splitext(infile)[0] + ".thumbnail"    if infile != outfile:        try:            im = Image.open(infile)            im.thumbnail(size, Image.ANTIALIAS)            im.save(outfile, "JPEG")        except IOError:            print "cannot create thumbnail for '%s'" % infile


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

from PIL import Imagebasewidth = 300img = 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')


I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you.

One important hint, though: Replace

im.thumbnail(size)

with

im.thumbnail(size,Image.ANTIALIAS)

by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.