In the PHP manual for base64_encode() I saw the following script for outputting an image.
Because imagepng outputs bool or image stream directly to output. So, in order to get image data you should use output buffers like this:
ob_start(); imagepng($im); $image = ob_get_contents(); ob_end_clean(); echo '';