4

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
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • possible duplicate of [how to create a base64encoded string from image resource](http://stackoverflow.com/questions/8502610/how-to-create-a-base64encoded-string-from-image-resource) – lonesomeday Nov 07 '13 at 16:04
  • Take a look at [this](http://stackoverflow.com/a/8502656/2959229) – user2959229 Nov 07 '13 at 16:05

1 Answers1

7

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);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337