[Image-SIG] Deliver me from Kludgehood - PIL, filesystems and state

Kevin Cazabon kevin_cazabon@hotmail.com
Fri, 6 Dec 2002 14:30:01 -0500


This is a multi-part message in MIME format.

------=_NextPart_000_0017_01C29D33.F5FF5700
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Yes, it's easy to send the image over the Internet without writing it to
disk:

write the image to a StringIO object, then stream that object with a http
header that reads:  "Content-Type: image/jpg" with the size/etc. there.

I do it with one of my scripts, here's the script itself attached (it does
some resizing and stuff too, strip out what you don't need)

Kevin Cazabon.


------=_NextPart_000_0017_01C29D33.F5FF5700
Content-Type: text/plain;
	name="sizeImage.py"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
	filename="sizeImage.py"

#!/usr/bin/python -u

# SizeImage
# by Kevin Cazabon, kevin@cazabon.com
# Copyright 2002, all rights reserved
# released under the GNU General Public License, version 2

# This cgi will dynamically resize image files based on the query string
# See photoAlbum.cgi for example of usage.

# user settings

largestWidth =3D 1024
largestHeight =3D 768
imageDir =3D "/home/httpd/html/photoAlbum"
defaultCategory =3D "Miscellaneous"

# imports
import Image, sys, string, os, cgi, StringIO

# Gather the input data and validate it
try:
    inputData =3D cgi.FieldStorage()

    if inputData.has_key("maxWidth"):
        maxWidth =3D int(min(string.atof(inputData["maxWidth"].value), =
largestWidth) + 0.5)
    else:
        maxWidth =3D largestWidth

    if inputData.has_key("maxHeight"):
        maxHeight =3D int(min(string.atof(inputData["maxHeight"].value), =
largestHeight) + 0.5)
    else:
        maxHeight =3D largestHeight

    if inputData.has_key("category"):
        category =3D os.path.split(inputData["category"].value)[-1]   # =
just so there's no path-playing games from the user
    else:
        category =3D defaultCategory

    if inputData.has_key("filename"):
        filename =3D inputData["filename"].value
        if string.lower(filename[-3:]) not in ["jpg", "peg", "tif", =
"gif", "png"]:
            print "Content-Type: text/html\n\n"
            print "Invalid Image File Requested: %s\nOnly Jpeg, TIFF, =
GIF, and PNG formats supported." %filename
            sys.exit(-1)
        filename =3D os.path.join(imageDir, category, =
os.path.split(filename)[-1])    # also so there's no path-playing games
    else:
        print "Content-Type: text/html\n\n"
        print "No image file requested!\n\n%s" %inputData
        sys.exit(-1)

except Exception, errorMsg:
    print "Content-Type: text/html\n\n"
    print "Error processing query string: %s" %inputData
    print "\n\n<p>%s\n<p>%s" %(Exception, errorMsg)
    sys.exit(-1)

if os.path.isfile(filename):
    try:
        image =3D Image.open(filename)
        imAspect =3D float(image.size[0]) / float(image.size[1])
        outAspect =3D float(maxWidth) / float(maxHeight)
        if imAspect > outAspect:
            # use maxWidth for sizing
            image =3D image.resize((maxWidth, int(maxWidth / imAspect + =
0.5)))
        else:
            # use maxHeight for sizing
            image =3D image.resize((int(maxHeight * imAspect + 0.5), =
maxHeight), Image.BICUBIC)

        # save the image to stdout
        sfp =3D StringIO.StringIO()
        image.save(sfp,'jpeg')

    except Exception, errorMsg:
        print "Content-Type: text/html\n\n"
        print "Error occurred while processing Image (%s)<p>\n\n" =
%filename
        print "%s<p>\n%s" %(Exception, errorMsg)
        sys.exit(-1)

else:
    print "Content-Type: text/html\n\n"
    print "Error: requested image file does not exist: %s" %filename
    sys.exit(-1)

# if you got here, everything went ok, and the image is in spf, just =
send it home
try:
    print 'Content-Type: image/jpeg\n'  # Python adds the extra line =
feed to separate the header
    sys.stdout.write(sfp.getvalue())
    sys.exit(0)
except Exception, errorMsg:
    # something went wrong in writing to sys.stdout?
    print "Content-Type: text/html\n\n"
    print "Error Printing Image and Header to =
sys.stdout\n<p>\n%s<p>\n%s" %(Exception, errorMsg)
    sys.exit(-1)




------=_NextPart_000_0017_01C29D33.F5FF5700--