Home  >  Article  >  Backend Development  >  How to save remote images locally under PHP_PHP Tutorial

How to save remote images locally under PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:34:46701browse

Today, when I was sorting out information, I found a function that I had found before. Through this function, we can achieve the above function.

Main function:

Copy code The code is as follows:

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

if($filename=="") {
$ext=strrchr($url,".") ;
if($ext!=".gif" && $ext!=".jpg" && $ext!=".png") return false;
$filename=date("YmdHis").$ 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;
}

Code to get a picture:
Copy code The code is as follows:

$img=GrabImage("http://www.baidu.com/img/baidu_logo.gif","logo.gif");
if($img){
echo '';
}else{
echo "false";
}

This is to save google For the logo example, the obtained image is saved in the same directory.

Get a series of regular pictures (for example: 100 pictures named with numbers 1-100):
Copy code Code As follows:

for ($i=1;$i<=100;$i++){
$img=GrabImage("http://www.yourimagesite.com/images/$ i.gif","images/$i.gif");
}

The above www.yourimagesite.com is the URL of the image and needs to be modified by yourself. After the program is executed, all The pictures will be saved under the images directory.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322335.htmlTechArticleWhen I was sorting out the information today, I found a function that I found before. Through this function, we can realize the above function. Main function: Copy code The code is as follows: function GrabI...
Statement:
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