So let’s say you’ve got a folder with a load of images, and you want to display them as thumbnails.
One thing you certainly DON’T want to do is just load up the images and shrink them in the HTML – assuming that the images are large, this is a bandwidth hog, and an annoying experience for the user. Ideally, you’d want to use actual thumbnails – they’re smaller in terms of both filesize and dimensions.
I hacked together a little script to do this for me:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #!/usr/local/bin/python2.6 import Image import os PICDIR = './pics' THUMBDIR = '%s/thumbs' % PICDIR ratio = 0.8 THUMB_W = 125 THUMB_H = int(ratio * THUMB_W) THUMBSIZE = (THUMB_W, THUMB_H) #1 - delete everything under /thumbs all_thumbs = os.listdir(THUMBDIR) remove_count = 0 for thumb in all_thumbs: thumbpath = '%s/%s' % (THUMBDIR, thumb) os.remove(thumbpath) print 'removed %s' % thumbpath remove_count += 1 print 'Removed %d thumbnails' % remove_count #2 - for each image in the pic directory, generate a new thumbnail all_files = os.listdir(PICDIR) jpgs = [file for file in all_files if file.endswith('.jpg')] for jpg in jpgs: original = Image.open('%s/%s' % (PICDIR, jpg)) thumb = original.resize(THUMBSIZE, Image.ANTIALIAS) thumbpath = "%s/%s" % (THUMBDIR, jpg) thumb.save(thumbpath) print "wrote %s" % thumbpath |
now whenever I rsync image files from my local machine to my webserver, I can just run the script, et voila!: thumbnails ahoy!
Tags: programming, python, scripting