In fact, that's very easy to do.

You can use the
Output Control Functions of PHP for this.
- Start buffering the output by calling:
code:
ob_start();
- Then, let imagepng() send the image to the output. Instead of getting printed, PHP will store it in the output buffer.
code:
imagepng($main_image);
- Now, you read what imagepng() has outputted with ob_get_flush(). This function gives you the output AND stops the output buffering, so basically it's does the same as ob_get_contents() and ob_end_flush() together, which is interesting in our case.
code:
$png_output = ob_get_flush();
- Yay, you have a variable containing the PNG output!
You can now save it to a file and send the PNG output to the browser after all, by simply print()ing it. Don't forget your headers! 
Link: Comment by trucex on PHP: Output Control.
Argh, beaten by WDZ... the shame...
