获取网络图片并保存到指定目录

/**
* @return int
* 测试获取网络图片并保存到本地目录,保留原来文件名
*/
public function down_img()
{
$url = 'http://test2.jinpeiwang.cn/Uploads/file/20180207/1517997669982517.png';
$file_arr = explode('/', $url);
$filename = $file_arr[(count($file_arr) - 1)];//文件名称生成
$filepath = $_SERVER['DOCUMENT_ROOT'].'/Uploads/downImg';
//创建目录
$dir = iconv("UTF-8", "GBK", $filepath);
if (!file_exists($dir)){
mkdir ($dir,0777,true);
} else {
//文件已存在,修改权限
chmod($dir, 0777);
}
$state = @file_get_contents($url,0,null,0);//获取网络资源的字符内容
if($state){
ob_start();//打开输出
readfile($url);//输出图片文件
$img = ob_get_contents();//得到浏览器输出
ob_end_clean();//清除输出并关闭
$size = strlen($img);//得到图片大小
$fp2 = @fopen($filepath.'/'.$filename, "a");
fwrite($fp2, $img);//向当前目录写入图片文件,并重新命名
fclose($fp2);
return 1;
}
else{
return 0;
}

}

猜你喜欢

转载自www.cnblogs.com/lfjblog/p/10614023.html