Newbie has question that's not exactly Python...

Chris Gonnerman chris.gonnerman at usa.net
Mon Apr 2 20:52:29 EDT 2001


----- Original Message -----
From: "Gary Walker" <borealis3 at home.com>
Subject: Newbie has question that's not exactly Python...

> Here's the question:
>
> When a web app needs to produce an image, it's usually a trivial task:
> simply reference the image in the HTML code, and voila.
>
> How does one go about producing a dynamically generated image? That is to
> say, one that didn't exist until the python script ran? I hope I don't
have
> to save it to some tempfile, and reference *that* in my python code.

You could use the Python Imaging Library.  I'm no expert on it; I use
gdmodule,
but PIL is more "standard."  You would do something like this in a cgi:

    import sys
    from PIL import Image
    from StringIO import StringIO

    img = Image.open("background.gif")  # or Image.new(...) for a blank
image
    # ... do some drawing on the image ...
    sfp = StringIO()
    img.save(sfp, "gif")  # possibly with keyword options
    sys.stdout.write(sfp.getvalue())

The StringIO is required as the save() method of the Image object requires
seek() and tell() methods, so we can't just say

    img.save(sys.stdout, "gif")  # BIG NO NO

because sys.stdout may be attached to a pipe or socket.

As I said, I'm no expert on PIL, so your mileage may vary.  There may be an
easier way to do this... anyone else care to comment?












More information about the Python-list mailing list