Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve the reverse effect of imagecreatefromstring in PHP?

Tags:

php

image

php-gd

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
like image 389
ShadowHero Avatar asked Oct 20 '25 02:10

ShadowHero


1 Answers

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);
like image 189
Rocket Hazmat Avatar answered Oct 21 '25 16:10

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!