用php获取远程图片并把它保存到本地的代码
程序员文章站
2023-01-24 21:45:51
<?php
function grabimage($url,$filename="") {
if($url==""):return false;endif;
if($filename=="") {
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg"):return false;endif;
$filename=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;
}
$img=grabimage("http://news.bbc.co.uk/images/_1978837_detector_ap100.jpg","");
if($img):echo '<pre><img src="'.$img.'"></pre>';else:echo "false";endif;
?>
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);
}
function grabimage($url,$filename="") {
if($url==""):return false;endif;
if($filename=="") {
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg"):return false;endif;
$filename=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;
}
$img=grabimage("http://news.bbc.co.uk/images/_1978837_detector_ap100.jpg","");
if($img):echo '<pre><img src="'.$img.'"></pre>';else:echo "false";endif;
?>
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);
}
上一篇: winform 添加背景图 闪屏问题解决
下一篇: 兔子为什么不吃窝边草?