簡體   English   中英

保存來自 Google Places 的照片副本 API Place Photos using curl

[英]Save copy of a photo from Google Places API Place Photos using curl

我正在嘗試使用 curl 從 Google Place Photos 抓取一張照片並將其保存在我的服務器上。

根據Google API 文檔的請求格式如下:

https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CoQBegAAAFg5U0y-iQEtUVMfqw4KpXYe60QwJC-wl59NZlcaxSQZNgAhGrjmUKD2NkXatfQF1QRap-PQCx3kMfsKQCcxtkZqQ&sensor=true&key=AddYourOwnKeyHere

所以我嘗試了這個 function:

function download_image1($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
    curl_exec($ch);
    curl_close($ch); // closing curl handle
    fclose($fp); // closing file handle
}

download_image1($photo, "test.jpg");

..其中$photo包含請求 url。

這不起作用,它保存了一個帶有 header 錯誤的空圖像,這可能是因為請求不是照片的實際 url。 此外,在請求 url 中,不可能知道我將獲得哪個圖像擴展名(jpg、png、gif 等),所以這是另一個問題。

任何有關如何保存照片的幫助表示贊賞。

編輯:當我嘗試打開圖像時,我的圖像查看器軟件出現 header 錯誤“無法讀取文件頭”。 腳本本身沒有顯示任何錯誤。

我在這里找到了一個解決方案: http//kyleyu.com/?q = node / 356

它提供了一個非常有用的函數,可以在重定向后返回實際的URL:

function get_furl($url)
    {
    $furl = false;
    // First check response headers
    $headers = get_headers($url);
    // Test for 301 or 302
    if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
        {
        foreach($headers as $value)
            {
            if(substr(strtolower($value), 0, 9) == "location:")
                {
                $furl = trim(substr($value, 9, strlen($value)));
                }
            }
        }
    // Set final URL
    $furl = ($furl) ? $furl : $url;
    return $furl;
    }

因此,您將Google Place Photo請求uRL傳遞給此函數,它會在重定向后返回照片的實際網址,然后可以與CURL一起使用。 它還解釋了有時候,卷曲選項curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 並不總是有效。

https://stackoverflow.com/a/23540352/2979237

我們可以將上面的代碼最小化,改成get_header()的第二個參數加1 function like $headers = get_headers($url, 1); . 這將返回關聯值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM