How can I get a base64 string from an image resource in PHP? Note however, I made the image on the fly, so no URL exists.
Here is what I've tried, but it doesn't work:
echo 'data:image/png;base64,'.base64_encode($img);
This gives an error:
Warning: base64_encode() expects parameter 1 to be string, resource given
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With