2015-04-02 58 views
4

我一直在试图从API检索截图,但是当我解码图像并保存它时,我得到一个破碎的图像。以下是我正在使用的代码。如果您想测试它,我创建了一个包含谷歌响应的示例文件的tinyurl。谷歌PageSpeed Insights API截图到文件

$name = 'test'; 
$result = file_get_contents('http://tinyurl.com/q4smyod'); 
$result = json_decode($result, true); 
$decoded=base64_decode($result['screenshot']['data']); 
file_put_contents('img/'.$name.'.jpg',$decoded); 

回答

14

正如我在评论中提及了与PHP API工作时,问题正在于谷歌的加密所造成的误差。如果您遇到此问题,只需使用以下替换函数来修复编码。

$data = str_replace('_','/',$result['screenshot']['data']); 
$data = str_replace('-','+',$data); 
$decoded = base64_decode($data); 
+0

不错!它完美地工作。谢谢。有没有可能运行[runpagespeed](https://developers.google.com/speed/docs/insights/v2/reference/pagespeedapi/runpagespeed)来获得'screenshot.width'和'screenshot.height',而不是默认为'320px,240px'? – hyip 2016-02-10 14:15:54

+0

非常感谢.. !!完美的工作..! – Ritesh 2016-09-10 11:00:29

0

这应该有助于让你更接近你的目标。你没有定义的名字和你的json_decoding有点奇怪:

<?php 
    error_reporting(-1); 
    ini_set('display_errors', 'On'); 
    $result = file_get_contents('http://tinyurl.com/q4smyod'); 
    $name = 'test2'; 
    $result = json_decode($result, true); 

    $decoded = base64_encode($result['screenshot']['data']); 
    file_put_contents($name.'.jpg',$decoded); 

?> 
+0

这没有什么比改变我正在解码的方法。我知道这个名字没有在代码中声明,但正如我所提到的,该文件已经创建,但不正确。我希望这不会影响我获得真正答案的机会。 – James 2015-04-02 06:02:18

+0

你有一个真正的答案,你怎么能检查一个没有文件名的图像开始?现在您的数据正在以文件名写入文件,并且正确解码,也许您可​​以确定如何正确写入文件。 – MrTechie 2015-04-02 06:04:06

+0

如果你不需要帮助,那么也许你不应该问。 – MrTechie 2015-04-02 06:04:45