简体   繁体   中英

php base64 encode imagecreatetruecolor

I have a php script that generates an image then outputs the image as a png.

$img = imagecreatetruecolor($graphWidth,$graphHeight);
...
*drawing routines*
...
header("Content-type: image/png");
imagepng($img);

What I now need is to get the php script to base64 encode the image data and output that string (so I can eventually pass that encoded data to a java script which decodes and adds this image to a generated pdf).

I have tried many times to get it working myself using other stackoverflow posts/answers etc. but I don't understand enough about this technology to have gotten it to work.

Can someone help me with this please?

Thanks in advance,

Chris

The reason this doesn't work is because the image in $img is a resource, not an actual PNG image. When you call imagepng() , it outputs the image.

What I would do is create an output buffer, and base-64 encode it.

ob_start();
imagepng($img);
$buffer = ob_get_clean();
ob_end_clean();
echo base64_encode($buffer);

Don't forget to change your Content-Type header, as this is no longer image/png .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM