And this gets used how? Can you show the "using" page? Your PHP code is designed to be "called" by another page. For example, presume the script you posted is called "generateimg.php". Then you need to have another page (call it MyImageUsingPage.php) where you should have an image tag like:
to actually render the image you're generating.
If you're putting that PHP script in the middle of a regular page, I could understand why things would not go too well. Is that what you're doing?