Python: Resizing Images (Part 2)

Suppose you’d like to create thumbnails for your images of a specific size, say 128×128. Because this is a square image, any non-square image will be scaled out of proportion if you simply apply the resize method on it. To maintain aspect ratio for your images, you might like to use the following code:

from PIL import Image
import glob

def createThumbnails(width, height):
    imageFiles = glob.glob('*.JPG')
    thumbnailFolder = 'thumbnails/'
    counter = 1
    totalCount = len(imageFiles)
    size = width, height
    for imagePath in imageFiles:
        print 'Creating thumbnails of ' + imagePath + ' (' + str(counter) + ' of ' + str(totalCount) + ')...'
        image =
        image.thumbnail(size, Image.ANTIALIAS) + 'thumbnail' + imagePath)
        counter += 1

    print 'Thumbnail creation complete.'

createThumbnails(128, 128)

I am currently using Python v2.7 on Mac OS X 10.9.5.

Leave a Reply

Your email address will not be published. Required fields are marked *