通过 PHP 将 API URL 转换为“data:image/png;base64”

Convert API URL to “data:image/png;base64" by PHP

以下APIURL有一个PNG格式的输出:

http://qrfree.kaywa.com/?l=1&s=8&d=google.com

我想将 API URL 转换为“data:image/png;base64” (DATA URL / DATA URI) 与 PHP 下面的代码示例:

$image = ("<img src = http://qrfree.kaywa.com/?l=1&s=8&d=google.com"); // False! (only example!)
//or
$image = 'real-picture.png'; // True!

$imageData = base64_encode(file_get_contents($image));
$src = 'data:image/png;base64,'.$imageData;
echo '<img src="'.$src.'">';

但是,上面的代码是用指定格式的真实图片工作的,如果用API URL代替,则无法读取图片路径。 代码应该如何更正?

假设网络请求 http://qrfree.kaywa.com/?l=1&s=8&d=google.com returns 类型为 image/png 的图像,您可以...

$image = "http://qrfree.kaywa.com/?l=1&s=8&d=google.com";
echo '<img src="data:image/png;base64,', 
    base64_encode(file_get_contents($image)),
    '">';

file_get_contents() 需要有效的文件名或有效的 http(s) 请求。您的代码传递了一些以 HTML <img ...

开头的内容