Create thumbnails in Python

I needed a script that would take a folder of pictures, resize the pictures, save them in a new folder and also make square thumbnails with the picture centered in the thumbnail. This Python script that I wrote does this very task quickly and produces lean images ( for example resulting thumbnails are 8 Kb comparing to Photoshop that for some reason was giving me images that are 5-8 times as heavy, 45 Kb for a 65×65 image)

The script also produces HTML code that you can just cut and paste into a responsive gallery like

You need to have PIL and Python installed to run this script.
Here’s the script:

[sourcecode language=”python”]

#!/usr/bin/env python
# encoding: utf-8

This script takes a folder named ‘photos’, creates two folders to store resized photos and thumbnails

Created by Maksim Surguy on 2012-04-09.


import os
from PIL import Image

def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):

def main():

# set max image dimensions
max_width = 640
max_height = 400

# set thumbnail size
thumb_size = (65, 65)

# optional – set the folder names if different names needed
photo_source_folder = "photos"
output_big_folder = "pics"
output_thumb_folder = "thumbs"

# do not edit below this line
htmlsource = ""
thumb_box = (0,0)

source_folder = os.getcwd() + "/" + photo_source_folder + "/"
current_folder = os.getcwd()+ "/"
ensure_dir(current_folder+ output_big_folder + "/")
ensure_dir(current_folder+ output_thumb_folder + "/")

dirList = [fname for fname in os.listdir(source_folder)
if fname.lower().endswith(".png") or fname.lower().endswith(".jpg")]
for fname in dirList:
print "Resizing %s" % fname
htmlsource += ‘<li><a href="#"><img src="%s/%s" data-large="%s/%s" alt="image" data-description="&nbsp;" /></a></li>n’%(output_thumb_folder,fname,output_big_folder, fname)

image = + fname)
if image.size[0] <= 640 and image.size[1] <= 400: + output_big_folder + "/" + fname, "JPEG", quality = 92)
image_big = image.copy()
image_big.thumbnail((max_width, max_height), Image.ANTIALIAS) + output_big_folder + "/" + fname, "JPEG", quality = 92)

image.thumbnail(thumb_size, Image.ANTIALIAS)
thumb_box = ( thumb_size[0]/2 – image.size[0]/2 , thumb_size[1]/2 – image.size[1]/2)
thumbnail = ("RGB", thumb_size)
thumbnail.paste(image, thumb_box) + output_thumb_folder + "/" + fname, "JPEG", quality = 90)

open("output.html", "w").write(htmlsource)

if __name__ == ‘__main__’:


You can download the script here:

You may also like

More in Code Blog
Build mobile apps faster with PhoneGap

Native mobile apps within hours, not weeks?  How so, you say? For example you need to built a company directory,...