Dynamic image creation for the web...
Benjamin Niemann
pink at odahoda.de
Sun Aug 28 09:11:28 EDT 2005
Tompa wrote:
> Hi,
>
> I would like to create images on the fly as a response to an http request.
> I can do this with PIL like this (file create_gif.py):
> from PIL import Image, ImageDraw
>
> print 'Status: 200 OK'
> print 'Content-type: text/html'
> print
> print '<HTML><HEAD><TITLE>Python Dynamic Image Creation
> Test</TITLE></HEAD>' print '<BODY>'
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> im.save("images/tmp.gif");
> print '<img src="/scripts/images/tmp.gif">'
> print '</BODY>'
>
>
> However, I would like to 1) avoid saving the image in a file on disk and
> 2) separate the HTLM code from the python image creation code.
>
> Something like this is what I have in mind:
> (file index.html):
> <html>
> <head><meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
> <title>Python Dynamic Image Creation</title>
> </head>
> <IMG SRC="/scripts/create_image.py" ALT="Image created on the fly...">
> </html>
>
> and in file create_image.py:
> from PIL import Image, ImageDraw, ImageFont
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
>
>
> Unfortunately this does not work :-(
> What is missing?
You are almost there. Your create_image.py does not return anything to the
browser yet.
First return proper HTTP headers, e.g.
sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/gif\r\n')
sys.stdout.write('\r\n')
(Your prints above are mostly equivalent, but do not output the correct \r\n
as line terminator - at least on UNIX style systems. Most webservers
tolarate this, if it's coming from a CGI - but doing it right and not
relying on a certain server behaviour is not bad anyway ;)
Then check the PIL docs to find out, how to output the image to sys.stdout
(instead of writing to a file).
--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
More information about the Python-list
mailing list