Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

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

2 Answers

0 votes
by (106k points)

To resize an image using PIL and maintain its aspect ratio you need to define a maximum size. After defining the maximum size you need to compute a resize ratio by using the following formula which is min(maxwidth/width, maxheight/height).

Below is the code example which will guide you on how to write the code for resizing the image using PIL.

import os, sys

import Image

size = 128, 128

for infile in sys.argv[1:]:

outfile = os.path.splitext(infile)[0] + ".thumbnail"

if infile != outfile:


im =

im.thumbnail(size, Image.ANTIALIAS), "JPEG")

except IOError:

print("cannot create thumbnail for '%s'" % infile)

0 votes
by (20.3k points)

The 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 of 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. You can change the "base width" to any other number to change the default width of your images.

from PIL import Image

basewidth = 300

img ='somepic.jpg')

wpercent = (basewidth/float(img.size[0]))

hsize = int((float(img.size[1])*float(wpercent)))

img = img.resize((basewidth,hsize), Image.ANTIALIAS)'sompic.jpg') 

Browse Categories