I have created an image with ImagePng(). I dont want it to save the image to the file system but want to output it on the same page as base64 encode inline Image, like
print '<p><img src="data:image/png;base64,'.base64_encode(ImagePng($png)).'" alt="image 1" width="96" height="48"/></p>';
which does not work.
Is this possible in a single PHP file at all?
Thanks in advance!
I had trouble using the ob_get_contents() when using PHP with AJAX, so I tried this:
$id = generateID(); //Whereas this generates a random ID number
$file="testimage".$id.".png";
imagepng($image, $file);
imagedestroy($image);
echo(base64_encode(file_get_contents($file)));
unlink($file);
This saves a temporary image file on the server and then it is removed after it is encoded and echoed out.
The trick here will be to use output buffering to capture the output from imagepng()
, which either sends output to the browser or a file. It doesn't return it to be stored in a variable (or base64 encoded):
// Enable output buffering
ob_start();
imagepng($png);
// Capture the output and clear the output buffer
$imagedata = ob_get_clean();
print '<p><img src="data:image/png;base64,'.base64_encode($imagedata).'" alt="image 1" width="96" height="48"/></p>';
This is adapted from a user example in the imagepng()
docs.
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