Home > php教程 > php手册 > 获取远程图片并保存的本地的方法实现

获取远程图片并保存的本地的方法实现

WBOY
Release: 2016-06-07 11:35:52
Original
1253 people have browsed it

根据图片的url,获取远程图片,利用curl进行图片的下载,并进行存储,最后返回图片的相关保存信息。
function getImage($url,$save_dir='',$filename='',$type=0){<br>             if(trim($url)==''){<br>                 return array('file_name'=>'','save_path'=>'','error'=>1);<br>             }<br>             if(trim($save_dir)==''){<br>                 $save_dir='./';<br>             }<br>             if(trim($filename)==''){//保存文件名<br>                 $ext=strrchr($url,'.');<br>             if($ext!='.gif'&&$ext!='.jpg'&&$ext!='.png'&&$ext!='.jpeg'){<br>                 return array('file_name'=>'','save_path'=>'','error'=>3);<br>             }<br>                 $filename=time().rand(0,10000).$ext;<br>             }<br>             if(0!==strrpos($save_dir,'/')){<br>                 $save_dir.='/';<br>             }<br>             //创建保存目录<br>             if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){<br>                 return array('file_name'=>'','save_path'=>'','error'=>5);<br>             }<br>             //获取远程文件所采用的方法<br>             if($type){<br>                 $ch=curl_init();<br>                 $timeout=5;<br>                 curl_setopt($ch,CURLOPT_URL,$url);<br>                 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);<br>                 curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);<br>                 $img=curl_exec($ch);<br>                 curl_close($ch);<br>             }else{<br>                 ob_start();<br>                 readfile($url);<br>                 $img=ob_get_contents();<br>                 ob_end_clean();<br>             }<br>             //$size=strlen($img);<br>             //文件大小<br>             $fp2=@fopen($save_dir.$filename,'a');<br>             fwrite($fp2,$img);<br>             fclose($fp2);<br>             unset($img,$url);<br>             return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);<br>         }

AD:真正免费,域名+虚机+企业邮箱=0元

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template