#!/usr/bin/python from __future__ import division import cgitb; cgitb.enable() import os.path import sys import cgi import math import Image import cStringIO as StringIO MAX_SIZE = 1024 basepath = r"PATH TO IMAGES HERE" form = cgi.FieldStorage() filename = form.getfirst('file', '') size = form.getfirst('size', 'null') mode = None filename = os.path.normpath(basepath + "/" + filename) if not filename.startswith(basepath): filename = '' if size[0] in 'wh': mode = size[0] size = size[1:] try: size = int(size, 10) except ValueError: size = None if not filename or not size or size > MAX_SIZE: print "Content-type: text/plain\n" print "Error: invalid input." sys.exit() try: image = Image.open(filename) except IOError: print "Content-type: text/plain\n" print "Image not found." sys.exit() w, h = image.size # Fixed width if mode == 'w': perc = size / w newsize = (size, math.floor(h * perc)) # Fixed height elif mode == 'h': perc = size / h newsize = (math.floor(w * perc), size) # Maximum dimension else: if w == h: newsize = (size, size) elif w > h: newsize = (size, math.floor((size / w) * h)) else: newsize = (math.floor((size / h) * w), size) f = StringIO.StringIO() resized = image.resize(newsize, Image.ANTIALIAS) resized.save(f, 'JPEG', quality=50, progression=True) v = f.getvalue() print "Content-type: image/jpeg" print "Cache-control: max-age=%s" % (60 * 60 * 24 * 360,) # 1 year print sys.stdout.write(v) sys.stdout.flush()