#!/usr/bin/python
""" a CGI script that accepts a JPEG through a POST
and converts it, returning it directly

the user may then right-click and "copy"
@author: Pat Beirne <patb@pbeirne.com>
@version: 1.0
@date: 2009-12-01
"""

import cgi, cgitb, StringIO
from PIL import Image
import time

cgitb.enable()

start = time.time()	# how long will this take?

form = cgi.FieldStorage()	# pull the info from the POST
bw = form.getvalue("b_and_w")
size = form.getvalue("size")
rot = form.getvalue("rot")
format = form.getvalue("format")
jpeg = form.getvalue("f_name")

# ok, that works; now we have the JPEG
jpeg_f = StringIO.StringIO(jpeg)
i = Image.open(jpeg_f)
orig_size = i.size
orig_format = i.format

if size!="no_change":
  i.thumbnail((int(size),int(size)))
  
if bw=="on":
  i = i.convert("L")

if rot!="0":
  i = i.rotate(int(rot))

output_f = StringIO.StringIO()
if format=="png":
  i.save(output_f,"PNG")
else:
  i.save(output_f,"JPEG")
  
jpeg = output_f.getvalue()
stop = time.time() 		# how long did this take?

if format=="png":
  print "Content-type: image/png"
else:
  print "Content-type: image/jpeg"
#print "Content-type: text/html"
print

print jpeg			# and send it back

####### stats #######

f = open("/var/www/photo_stats.txt","a")
info = "%s original: %s/%s requested:%s/%s time-to-process: %2.2f sec" % \
              (time.ctime(),orig_size,orig_format,size,format,stop-start)
print >>f, info
