Dynamic image creation for the web...

Richard Lewis richardlewis at fastmail.co.uk
Sun Aug 28 06:47:21 EDT 2005


On Sun, 28 Aug 2005 09:50:17 +0000 (UTC), "Tompa" <tompa1969 at yahoo.com>
said:
> 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?
> 
It would be useful to know what web server software you're using. With
Apache you should be able to force it to tell clients that your scripts
are returning images by using the AddType directive form mod_mime
(http://httpd.apache.org/docs/2.0/mod/mod_mime.html.en#addtype).

The other thing you may need to check is the HTTP header of the
generated image. It should be possible to create an HTTP response from
your create_image.py script (as opposed to just an image) with a MIME
type of image/jpeg and manually insert the binary image data in the
response body...

Cheers,
Richard



More information about the Python-list mailing list