You're sending out htmls before your image headers are sent. The headers must be the first thing the browser should receive before any outputs at all.
The solution here would be that you separate the the code that generates the image and the code that echoes the normal html into two different scripts.
Consider the first script foo.php
that contains the code ONLY for image generation. Make sure you don't echo anything else here.
Then, have everything else (htmls & page contents) in a different script (lets say bar.php
). And place an image tag here such that it displays the image that the first script (foo.php) generates.
<img src="foo.php">