PHP: create image with ImagePng and convert with base64_encode in a single file?

Romaeus Percival picture Romaeus Percival · Feb 21, 2012 · Viewed 21.1k times · Source

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!

Answer

Michael Berkowski picture Michael Berkowski · Feb 21, 2012

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.