简体   繁体   English

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

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

The following API URL has an output in PNG image: 以下API URL在PNG图像中具有输出:

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

I want convert the API URL to “data:image/png;base64” (DATA URL / DATA URI) with the similar to the PHP code example below: 我想将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.'">';

However, the above code works with a real picture which has specified format and if replaced with the API URL, cannot read image path. 但是,以上代码适用于具有指定格式的真实图片,并且如果替换为API URL,则无法读取图像路径。 How the code should be corrected? 代码应如何更正?

Assuming a web request to http://qrfree.kaywa.com/?l=1&s=8&d=google.com returns an image of type image/png, you can do ... 假设对http://qrfree.kaywa.com/?l=1&s=8&d=google.com的网络请求返回的图像类型为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() expects either a valid file name or a valid http(s) request. file_get_contents()需要一个有效的文件名或一个有效的http(s)请求。 Your code was passing in something starting with some HTML <img ... 您的代码传递了一些以HTML <img ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM