I can help you with #3. You can handle this one of two ways:
Have your script write the image to a
temp file (somewhere within the webserver's heirarchy), and pass that filename to the browser.
Be sure you are done saving the file before you return the IMG
tag to the bowser.
Be sure to delete the file later.
Have a separate .cgi that generates the image (it
must return an apropriate ContentType header). Call that
.cgi from the IMG tag in your main script that is generating
the "text" of the page: