#!/usr/bin/python

import cgi
import sys, os.path
# PIL
import Image, ImageDraw

# to enable errors to be displayed in the browser:
#import cgitb; cgitb.enable()


# load image thumb to browser
def loadImage():
	im = Image.open("%s_thumb_%s%s" % (base, icon_width, ext))
	# send image to stdout (browser)
	im.save(sys.stdout, "JPEG")


# create new thumbnail
def createImage():
	# file exists
	if file_name and os.path.isfile(file_name):
		#Êopen image
		im = Image.open(file_name)
		# thumbnail image
		im.thumbnail((icon_width, icon_width), Image.ANTIALIAS)
		
		# save thumb file
		(base, ext) = os.path.splitext(file_name)
		im.save(open("%s_thumb_%s%s" % (base, icon_width, ext), "w"))
		
	else:
		# new image
		im = Image.new("RGB", (icon_width,icon_width), (255,255,0))
		draw = ImageDraw.Draw(im)
		# text message on image
		draw.text((5,5), "error: no file_name?", fill=(0,0,0))
	

if __name__ == "__main__":
	# basic cgi output header JPEG
	print "Content-type: image/jpeg\n"
	
	# init
	icon_width = 256
	
	# form fields to var assignment
	formdata = cgi.FieldStorage()
	file_name = formdata.getvalue('file', '')
	icon_width = int(formdata.getvalue('width', icon_width))
	
	# if file thumb in this size not exists:
	(base, ext) = os.path.splitext(file_name)
	if not os.path.isfile("%s_thumb_%s%s" % (base, icon_width, ext)) and file_name.find('..')==-1:
		# create and save thumb
		# call function to create image
		createImage()
	# load thumb
	loadImage()
	
	
