2015-04-02 57 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