There's no way to tell GD to return your image as a binary string, unfortunately. GD only supports writing to a file or to the screen. What we can do though is use output buffering to capture its output and then put it in a string.
ob_start();
imagepng($img);
$image = ob_get_clean();
echo 'data:image/png;base64,'.base64_encode($image);