#!/usr/bin/python
"""
 random_walk_0.cgi

 A CGI script to generate an image of a random walk
 (well, ok, not *very* random) using PIL, the Python Imaging Library.

 version 0 : just generate a few lines - one of which is random - 
             and output the image

 From the command line generate an image file :
   # comment out "Content-Type" line, and output straight to a file :
   $ ./random_walk_0.cgi > rw0.png
 or run it over the web :
   visit http://....../random_walk_0.cgi with a web browser.

 Jim Mahoney | cs.marlboro.edu | Sep 2012 | MIT License
"""
from PIL import Image, ImageDraw
from random import randint
from sys import stdout

def make_image():
    """ Return PIL Image of some lines with a random one. """
    image_mode = 'RGB'
    # colors are (red,green,blue) from 0 to 255
    background_color = (248, 250, 252)
    line_color = (160, 200, 230)
    image_size = (400, 400)     # in pixels
    line_width = 2  # also in pixels ... though docs suggest there may be a bug
    points = ((200,200), (200,100), (50,100), (50, 20))
    n_points = len(points)
    image = Image.new(image_mode, image_size, background_color)
    draw = ImageDraw.Draw(image)
    for i in range(n_points - 1):
        start_point = points[i]
        end_point = points[i + 1]
        draw.line((start_point, end_point), fill=line_color, width=line_width)
    last_point = randint(0, image_size[0]), randint(0, image_size[1])
    draw.line((points[-1], last_point), fill=line_color, width=line_width)
    return image

print "Content-Type: image/png\n"
print make_image().save(stdout, 'PNG')


