簡體   English   中英

從PHP中的URL下載圖像

[英]Downloading Images from URL in PHP

我有一個文件,在其中逐行讀取URL。 URL是指向圖像的鏈接。 所有圖像鏈接都可以在瀏覽器中使用。 現在,我要將它們下載到我的當前目錄。 為了記錄,我需要使用PHP腳本。

這是我獲取圖像的方式:

for ($j; $j< $count;$j++)

{
  // Get Image-URL as String and then do getImage
  $image = $arr[$j];
  $newname = $j;
  getImage($image, $newname);
}

function getImage($image, $newname)
{

    $ch = curl_init($image);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $rawdata=curl_exec ($ch);
    curl_close ($ch);
    $fp = fopen("$newname.jpg",'w');
    fwrite($fp, $rawdata); 
    fclose($fp);
}

但是問題是,我得到了所有圖像,只有最后一張是可見的。 其他我無法打開的文件,它們只有1KB

那我做錯了什么?

另外,我稍后還需要下載png文件,因此我可以將$ newname.jpg更改為$ newname.png嗎?

在此先感謝您,我確實需要一個快速的答案,已經坐在這里幾個小時,試圖找出答案。

為什么不使用stream_copy_to_stream

function getImage($image, $newname, $fileType = "jpg")
{
    $in = fopen($image, "r");
    $out = fopen("$newname.$fileType",'w');
    stream_copy_to_stream($in, $out); 
    fclose($in); fclose($out);
}

您也可以玩stream_set_read_buffer

stream_set_read_buffer($in, 4096);

剛剛用我們的頭像照片進行了測試。

$data = [
    "https://www.gravatar.com/avatar/42eec337b6404f97aedfb4f39d4991f2?s=32&d=identicon&r=PG&f=1",
    "https://www.gravatar.com/avatar/2700a034dcbecff07c55d4fef09d110b?s=32&d=identicon&r=PG&f=1",
];

foreach ($data as $i => $image) getImage($image, $i, "png");

完美運作。

調試:閱讀遠程頭以獲得更多信息? $ httpresponseheader

var_dump($http_response_header);

stream_get_meta_data

var_dump(stream_get_meta_data($in), stream_get_meta_data($out));

暫無
暫無

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

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