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

怎甘沉沦 提交于 2019-12-18 03:56:44

问题


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!


回答1:


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.




回答2:


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.




回答3:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!