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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top