2015-12-14 91 views
1

以下API URL在PNG图像输出:转换API网址为“数据:图像/ PNG;的base64" 由PHP

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

我想转换API URL为“数据:图像/ 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一个真实的画面,无法读取图像路径 代码应如何纠正?

回答

1

假设一个Web请求http://qrfree.kaywa.com/?l=1&s=8&d=google.com返回类型的图像/ 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 ...

+0

已修复! ,非常感谢“BareNakedCoder”。 – rapoli