How do I resize an image using PIL and maintain its aspect ratio?
Define a most size. Then, calculate a size magnitude relation by taking min(maxwidth/width, maxheight/height).
The proper size is oldsize*ratio.
There is after all additionally a library methodology to try to to this: the tactic Image.thumbnail.
Below is associate (edited) example from the PIL documentation.
import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile) + ".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 can size a picture (somepic.jpg) victimisation PIL (Python Imaging Library) to a dimension of three hundred pixels and a height proportional to the new dimension.
It will this by crucial what share three hundred pixels is of the initial dimension (img.size) and so multiplying the initial height (img.size) by that share. modification “basewidth” to the other variety to alter the default dimension of your pictures:
from PIL import Image basewidth = 300 img = Image.open('somepic.jpg') wpercent = (basewidth/float(img.size)) hsize = int((float(img.size)*float(wpercent))) img = img.resize((basewidth,hsize), Image.ANTIALIAS) img.save('sompic.jpg')