> php教程 > PHP源码 > 본문

PHP采集远程图片到本地实现代码

WBOY
풀어 주다: 2016-06-08 17:24:23
원래의
1090명이 탐색했습니다.

在php中要保存远程图片到自己服务器本地,我们需要先正则字符串中的内容图片,然后再利用相关函数把图片读取并保存到本地硬盘即可。

<script>ec(2);</script>
 代码如下 复制代码


header("Content-type:image/jpeg");
function read_url($str)
{
$file=fopen($str,"r");
while(!feof($file))
{
$result.=fgets($file,9999);
}
fclose($file);
return $result;

}

function save_img($str)
{
$result=read_url($str);
$result=str_replace(""","",$result);
$result=str_replace("'","",$result);

preg_match_all('/PHP采集远程图片到本地实现代码|>)/i',$result,$matches);

foreach($matches[1] as $value)
{
echo $value."
n";
//GrabImage($value,$filename="");
}
}

// $url 是远程图片的完整URL地址,不能为空。
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期
// 自动生成.

function GrabImage($url,$filename="") {
if($url==""):return false;endif;

$path="download/"; //指定存储文件夹

//若文件不存在,则创建;
if(!file_exists($path)){
mkdir($path);
}

if($filename=="") {
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg"):return false;endif;
$filename=$path.date("dMYHis").$ext;
}

ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);

$fp2=@fopen($filename, "a");
fwrite($fp2,$img);
fclose($fp2);

return $filename;
}
save_img("http://www.111cn.net");
?>

dedecms中图版保存到本地方法

 代码如下 复制代码

 if(!empty($saveremoteimg))
        {
                $body = stripslashes($body);
                $img_array = array();
                preg_match_all("/(src|SRC)=[""|'| ]{0,}(http://(.*).(gif|jpg|jpeg|bmp|png))/isU",$body,$img_array);
                $img_array = array_unique($img_array[2]);
                set_time_limit(0);
                $imgUrl = $img_dir."/".strftime("%Y%m%d",time());
                $imgPath = $base_dir.$imgUrl;
                $milliSecond = strftime("%H%M%S",time());
                if(!is_dir($imgPath)) @mkdir($imgPath,0777);
                foreach($img_array as $key =>$value)
                {
                        $value = trim($value);
                        $get_file = @file_get_contents($value);
                        $rndFileName = $imgPath."/".$milliSecond.$key.".".substr($value,-3,3);
                        $fileurl = $imgUrl."/".$milliSecond.$key.".".substr($value,-3,3);
                        if($get_file)
                        {
                                $fp = @fopen($rndFileName,"w");
                                @fwrite($fp,$get_file);
                                @fclose($fp);
                        }
                        $body = ereg_replace($value,$fileurl,$body);
                }
                $body = addslashes($body);
        }

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!