#!/usr/bin/env python # # pic2html v0.2a # # A small cgi-script to convert binary-pictures to # colorized html-data. # # Author: Rikard Bosnjakovic , 2001-03-27 # updated 2003-09-08 # updated 2004-08-01 # import cgi, Image, os, StringIO, sys, tempfile, urllib print "Content-type: text/html\n" # max size (width or height, in pixels) MAXSIZE = 200 # read the file to use as the background and remove all crappy chars txt = open("source").read() for i in "<>&\n ": txt = txt.replace(i, "") # get the url to the picture storage = cgi.FieldStorage() if not storage.has_key("url"): print "Empty URL." sys.exit() url = storage["url"].value if urllib.unquote(url).find("file://") > -1: print "Not allowed to use file://." sys.exit() try: urlfile = urllib.urlopen(url) except IOError: print "An error occured while retrieving the file." sys.exit() pagedata = urlfile.read() try: im = Image.open(StringIO.StringIO(pagedata)) except: print "ERROR - ", sys.exc_type, ":", sys.exc_value print sys.exit() ## gray scale pictures doesn't work yet. # is the color an integer (index) or a tuple (palette)? if type(im.getpixel((0,0))) == type(0): # palette. obtain it and put them in a list of 3-tuples (R, G, B) palette = im.getdata().getpalette() pal = [ tuple(palette[3*i:3*i+3]) for i in range(len(palette)/3) ] else: # the palette is stored in each pixel, not indexed pal = () # rescale the picture to better proportionals x = im.size[0] y = im.size[1] if x>1000 or y>1000: print "Too big picture, try a smaller one (below 1000*1000)." sys.exit() if x > MAXSIZE: im = im.resize((MAXSIZE, (MAXSIZE*y)/x)) x = im.size[0] y = im.size[1] if y > MAXSIZE: im = im.resize(((MAXSIZE*x)/y, MAXSIZE)) im = im.resize((im.size[0], im.size[1]/2)) # print the picture in ascii and save it tempfile.tempdir = "/home/bos/public_html/pic2html/tmp/" tmpname = tempfile.mktemp(".html") f = open(tmpname, "a") pagedata = "pic2html v0.2 <bos@hack.org" pagedata += ">" pagedata += '
'
print pagedata
f.write(pagedata+"\n")

filecount = 0
lastcol = ()
newcol = ()
for y in range(im.size[1]):
    pagedata = ""
    for x in range(im.size[0]):
        if pal:
            newcol = pal[im.getpixel((x,y))]
            coltuple = tuple(map(ord, newcol))
        else:
            newcol = coltuple = im.getpixel((x,y))
        if not newcol == lastcol:
            pagedata += "" % coltuple
            lastcol = newcol

        pagedata += txt[filecount]
        filecount += 1
        if filecount > len(txt)-1:
            filecount = 0
    print pagedata
    f.write(pagedata+"\n")

pagedata = "
" print pagedata f.write(pagedata+"\n") f.close() # log the request if os.environ.has_key("REMOTE_HOST"): host = os.environ["REMOTE_HOST"] else: host = os.environ["REMOTE_ADDR"] log = open("log.txt", "a") log.write (host+" - "+url+" - ("+tmpname+")\n") log.close()