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!
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.
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.
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).
来源:https://stackoverflow.com/questions/9370847/php-create-image-with-imagepng-and-convert-with-base64-encode-in-a-single-file