Embedding a Dynamic Image in CGI Output
By Randal L. Schwartz
Developers working with CGI scripting are frequently confused about how to return a dynamic image as part of a script's response. I'm frequently asked questions such as: "How can I embed an image in my HTML?" or "How can I return two different MIME types in one response?" Well, you can't.
But you can form a CGI response that generates a graphic that changes depending on the basis of the query. Simply put, the HTML response to the query has an embedded IMG tag that calls another CGI invocation (either the same script or a companion script). There's enough information in the second query for the script to generate the appropriate image.
The key here is "enough information." The first CGI response could calculate everything needed to generate this picture, save the image into a temporary directory on the server under a unique name, and then return the URL for that name. Or, as we're doing here, the image-fetching URL (the one that calls the second invocation) can contain all of the information to generate the image itself. The first method requires you to clean up the temporary directory frequently, while the second suffers if a graphic is expensive to calculate. So, as with everything else on the Web, trade-offs must be made.
As an example of the latter "no server-side storage" strategy, let's examine a simple application. A nice module generating various bar code types showed up on the CPAN recently, and I wanted to play with it. The module uses the GD library to generate a PNG image.