PHP 下载远程图片

时间:2021-10-31 01:58:41

方法一:file_get_contents

/**-- 下载远程文件 --**/
function down_img($url){
set_time_limit(60);
if($url==""){
return false;
}
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg" && $ext!=".png" && $ext!=".jpeg"){
return false;
}
if(!file_exists($this->uploadpath)){
dir_create($this->uploadpath);
}
$filename=$this->getname($ext);
$img = file_get_contents($url);
$fp2=@fopen($this->uploadpath.$filename, "a"); //此处可加上图片存放路径
fwrite($fp2,$img);
fclose($fp2);
/*
$imgwh=getimagesize($this->uploadpath.$filename);
if($imgwh[0]>480 || $imgwh[1]>480){
$this->image->thumb($filename, 480, 480);
}*/
return $this->urlpic.$filename; //返回新的图片名称
}
/**-- 下载远程ICON .175x175-75.jpg .100x100-75.jpg 350x350-75.jpg 512x512-75.jpg --**/
function down_icon($url,$size){
if($url==""):return false;endif;
$ext='.jpg';
$num=strrpos($url,'.');
$data = substr($url, 0,$num);
$data=$data.$size; if(!file_exists($this->uploadpath)){
dir_create($this->uploadpath);
}
$filename=$this->getname($ext);
$img = file_get_contents($data);
$fp2=@fopen($this->uploadpath.$filename, "a"); //此处可加上图片存放路径
fwrite($fp2,$img);
fclose($fp2);
return $this->urlpic.$filename; //返回新的图片名称
}
/**-- 获取附件名称 @param $fileext 附件扩展名 --**/
function getname($fileext){
return date('Ymdhis').rand(100, 999).$fileext;
}

方法二:redefile

/**-- 下载远程文件 --**/
function down_img($url){
set_time_limit(60);
if($url==""){
return false;
}
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg" && $ext!=".png" && $ext!=".jpeg"){
return false;
}
if(!file_exists($this->uploadpath)){
dir_create($this->uploadpath);
}
$filename=$this->getname($ext);
ob_start(); //开启缓冲区 $opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>25,
)
);
$context = stream_context_create($opts); readfile($url, false, $context);
$img = ob_get_contents();
ob_end_clean();
$fp2=@fopen($this->uploadpath.$filename, "a"); //此处可加上图片存放路径
fwrite($fp2,$img);
fclose($fp2);
/*
$imgwh=getimagesize($this->uploadpath.$filename);
if($imgwh[0]>480 || $imgwh[1]>480){
$this->image->thumb($filename, 480, 480);
}*/
return $this->urlpic.$filename; //返回新的图片名称
}
/**-- 下载远程ICON .175x175-75.jpg .100x100-75.jpg 350x350-75.jpg 512x512-75.jpg --**/
function down_icon($url,$size){
if($url==""):return false;endif;
$ext='.jpg';
$num=strrpos($url,'.');
$data = substr($url, 0,$num);
$data=$data.$size; if(!file_exists($this->uploadpath)){
dir_create($this->uploadpath);
}
$filename=$this->getname($ext);
ob_start();
readfile($data);
$img = ob_get_contents();
ob_end_clean(); $fp2=@fopen($this->uploadpath.$filename, "a"); //此处可加上图片存放路径
fwrite($fp2,$img);
fclose($fp2); return $this->urlpic.$filename; //返回新的图片名称
}
/**-- 获取附件名称 @param $fileext 附件扩展名 --**/
function getname($fileext){
return date('Ymdhis').rand(100, 999).$fileext;
}