All web sites use images. However, most images are static: they're generated in advance and stored on the server. This way, a request to retrieve the image can be processed quickly. This week's article will discuss something completely different: sending images that are generated on-the-fly in response to a request.
Content-type: text/plain
When a web browser (or user agent) sees this MIME type, it knows that it is dealing with plain text. In plain text, symbols such as < or > will not be interpreted as HTML tags and line breaks will be displayed as they are in the source file. To enable HTML, the following is used:
Content-type: text/html
In a similar manner, images can be returned by a CGI script. Simply use an appropriate header:
Content-type: image/gif
or
Content-type: image/jpeg
After sending the header and a blank line (to indicate that there are no more headers), the actual content is transmitted. For example, consider a rather simple, silly shell script such as this one:
#! /bin/sh echo "Content-type: image/jpeg" echo "" cat someimage.jpgIf this script were named sendimage and stored in the cgi-bin directory, then, the image could be displayed by pointing a web browser to:
http://server.name/cgi-bin/sendimage
Similarly, the image could be displayed with the following HTML:
<img src="/cgi-bin/sendimage">
The web browser will treat your CGI script as an ordinary graphic. (In fact, it can't even tell the difference.) Obviously, this example is quite simple. Let's try something a little bit more complex.
If you have the proper software installed (NetPBM and jpegsrc*), the following CGI script will generate a jpeg image 256x256 pixels that approximates a small section of a starry night:
#! /bin/sh echo "Content-type: image/jpeg" echo "" ppmforge -night -width 256 -height 256 | cjpeg
To see a cloudy sky, try the following:
#! /bin/sh echo "Content-type: image/jpeg" echo "" ppmforge -clouds -width 400 -height 400 | cjpeg
The examples above are especially effective when used as the background for an HTML page:
<body background="/cgi-bin/stars" text="white" bgcolor="black">
Putting all these pieces together with a little Perl glue, you'll see a really Great Finale to this article. (If you're interested, the source is available here.)
Note: You may encounter problems trying to run these programs on Windows95 or NT. The programs and scripts discussed in this article have been tested on Perl 5.004 running the Apache web server; it's the most popular web server software in the world. Also, if you're interested in a high performace, high quality, free operating system for your PC or Macintosh computer, try Linux. |