Are you trying to spit out the image data straight onto the html page along with the html content? If so that would explain the problem of having the ASCII data showing up. What should work is if you generate your dynamic html, and then have an image tag that looks like:
<image src="/cgi-bin/imagegenerator.cgi">
What should be happening is, the browser will make a request to your html generating cgi, then it will start making separate requests for each image it needs, and call your image generating cgi.....
cephas