Romaeus Percival
Romaeus Percival

Reputation: 181

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

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!

Upvotes: 18

Views: 26075

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270767

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.

Upvotes: 36

SOFe
SOFe

Reputation: 8224

If you do not wish to store to an explicit file, and you are already using ob_start() for something else (so you cannot use ob_start for this case without a lot of refactoring), you can define your own stream wrapper that store a stream output to a variable.

You use stream_wrapper_register to register a new stream wrapper, and implement its stream_write method to write it to a variable whose value you can retrieve later. Then you pass this stream (actually you just need to pass the URI for this stream) to imagepng. imagepng wanting to close your stream won't bother you, as long as your stream wrapper doesn't destroy the data when it is closed (stream_close method called).

Upvotes: 2

SyntaxLAMP
SyntaxLAMP

Reputation: 985

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.

Upvotes: 5

Related Questions