簡體   English   中英

使用PHP從遠程服務器下載多個圖像(很多圖像)

[英]Download multiple images from remote server with PHP (a LOT of images)

我試圖從外部服務器下載大量文件(約3700張圖像)。 這些圖像各自從30KB到200KB。

當我在1張圖像上使用copy()函數時,它可以工作。 當我在循環中使用它時,我得到的只是30B圖像(空圖像文件)。

我嘗試使用copycURLwgetfile_get_contents 每次,我要么得到很多空文件,要么根本沒有。

以下是我嘗試過的代碼:

wget的:

exec('wget http://mediaserver.centris.ca/media.ashx?id=ADD4B9DD110633DDDB2C5A2D10&t=pi&f=I -O SIA/8605283.jpg');

復制:

if(copy($donnees['PhotoURL'], $filetocheck)) {
  echo 'Photo '.$filetocheck.' updated<br/>';
}

卷曲:

$ch = curl_init();
$source = $data[PhotoURL];
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);

$destination = $newfile;
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

似乎沒有什么工作正常。 不幸的是,我沒有太多選擇一次下載所有這些文件,我需要一種方法讓它盡快工作。

非常感謝,Antoine

逐個獲取它們可能會非常緩慢。 考慮將它們分成20-50個圖像包並用多個線程抓取它們。 這是讓你入門的代碼:

$chs = array();
$cmh = curl_multi_init();
for ($t = 0; $t < $tc; $t++)
{
    $chs[$t] = curl_init();
    curl_setopt($chs[$t], CURLOPT_URL, $targets[$t]);
    curl_setopt($chs[$t], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($cmh, $chs[$t]);    
}

$running=null;
do {
    curl_multi_exec($cmh, $running);
} while ($running > 0);

for ($t = 0; $t < $tc; $t++)
{
    $path_to_file = 'your logic for file path';
    file_put_contents($path_to_file, curl_multi_getcontent($chs[$t]));
    curl_multi_remove_handle($cmh, $chs[$t]);
    curl_close($chs[$t]);
}
curl_multi_close($cmh);

我最近使用這種方法獲取了數百萬張圖片,因為一個接一個就需要一個月。

您一次抓取的圖像數量應取決於其預期大小和內存限制。

我使用了這個功能並且工作得很好。

function saveImage($urlImage, $title){

    $fullpath = '../destination/'.$title;
    $ch = curl_init ($urlImage);
    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);
    if(file_exists($fullpath)){
        unlink($fullpath);
    }
    $fp = fopen($fullpath,'x');
    $r = fwrite($fp, $rawdata);

    setMemoryLimit($fullpath);

    fclose($fp);

    return $r;
}

結合另一個,以防止內存溢出:

function setMemoryLimit($filename){
   set_time_limit(50);
   $maxMemoryUsage = 258;
   $width  = 0;
   $height = 0;
   $size   = ini_get('memory_limit');

   list($width, $height) = getimagesize($filename);
   $size = $size + floor(($width * $height * 4 * 1.5 + 1048576) / 1048576);

   if ($size > $maxMemoryUsage) $size = $maxMemoryUsage;

   ini_set('memory_limit',$size.'M');

}

暫無
暫無

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

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