Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.

like image 281
saturdayplace Avatar asked Nov 07 '08 23:11

saturdayplace


People also ask

How do you preserve aspect ratio when scaling images?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.


2 Answers

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, sys import Image  size = 128, 128  for 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 
like image 144
gnud Avatar answered Oct 26 '22 09:10

gnud


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 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') 
like image 22
tomvon Avatar answered Oct 26 '22 09:10

tomvon