用php下载网络上指定的URL的图片,具体思路和所使用的函数有哪些?

解决方案 »

  1.   

    如果不防外链,就file_get_contents,否则就fsockopen,或者curl。
      

  2.   

    file_get_contents 获得图片数据,那怎么保存到硬盘呢?
      

  3.   

    这个是我以前写的一个段子
    <?php
    //实现了采集网页中的图片,自动保存到本地的功能。
    //使用了Snoopy类
    require_once("snoopy.class.php");
    $img_array = array(); 
    $img_path = realpath("img").'/'.date("Y-m-d").'/'; //采集远程图片保存地址$snoopy = new Snoopy;
    $snoopy->fetch("http://www.tool.com/test/dome.htm");$body = $snoopy->results;
    //preg_match_all("/(src|src)=[\"|\'|]{0,}(http:\/\/(.*)\.(jpg|jpeg|png))/isu",$body,$img_array);//采集网页图片的正则
    preg_match_all("/http:\/\/.*?\.(jpg|jpeg|png|gif)/is",$body,$img_array);
    $img_array = array_unique($img_array[0]);//array_unique() 接受 array 作为输入并返回没有重复值的新数组。
    //print_r($img_array);
    foreach($img_array as $key => $value){
      $filetime = time();
      $filename = date("ymdhis",$filetime).rand(1,999).'.'.substr($value,-3,3); 
      $snoopy->fetch($value);
      $get_file = $snoopy->results;
      echo "<img src=".$value."><br>\n";
      if( mkdirs($img_path) )
       {
        $fp = fopen($img_path.$filename,"w");
        fwrite($fp,$get_file);
        fclose($fp);
        //@sleep(6);
       }  
    }function mkdirs($dir)
    {
     if(!is_dir($dir)){
      if(!mkdirs(dirname($dir))){
       return false;}
      if(!mkdir($dir,0777)){
       return false;}
     }
     return true;

     //$str ='fasfsdafsa<img src=http://www.bokenya.jp/idolbb/img/preview_new/DMSM-7140/19.jpg />';?>
      

  4.   

    注意:“http://www.tool.com/test/dome.htm”是你要采集的页面“preg_match_all("/http:\/\/.*?\.(jpg|jpeg|png|gif)/is",$body,$img_array);
    ” 这个正则要根据实际来调整的也可以用“preg_match_all("/http:\/\/.*?\.jpg/is",$body,$img_array);”正则要跟后面的 取值配合使用的。
      

  5.   


    <?php
    $img_url = 'http://avatar.profile.csdn.net/2/E/0/2_Alex_Best.jpg';
    $img_content = file_get_contents($img_url);
    file_put_contents('alex_best.jpg',$img_content);