PHP 抓取网页图片并且另存为的实现代码

yipeiwu_com5年前PHP代码库
下面是源代码,及其相关解释
复制代码 代码如下:

<?php
//URL是远程的完整图片地址,不能为空, $filename 是另存为的图片名字
//默认把图片放在以此脚本相同的目录里
function GrabImage($url, $filename=""){
//$url 为空则返回 false;
if($url == ""){return false;}
$ext = strrchr($url, ".");//得到图片的扩展名
if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp"){echo "格式不支持!";return false;}
if($filename == ""){$filename = time()."$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;
}
//测试
GrabImage("//www.jb51.net/images/logo.gif", "as.gif");
?>

ob_start : 打开输出缓冲
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. (输出是在内部缓冲储存)
//
readfile : 读入一个文件并写入到输出缓冲
返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。
//

ob_get_contents : Return the contents of the output buffer(返回输出缓冲的内容)
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn't active. (如果输出缓冲没有活动(打开),则返回 FALSE)
//
ob_end_clean() : Clean (erase) the output buffer and turn off output buffering(清除输出缓冲)
This function discards(丢弃) the contents of the topmost output buffer and turns off this output buffering.(丢弃并且关掉) If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called. (如果要用缓冲内容,则在清理输出缓冲之前要先调用 ob_get_contents())The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

相关文章

php抽象方法和抽象类实例分析

本文实例讲述了php抽象方法和抽象类。分享给大家供大家参考,具体如下: 什么是抽象方法? 在类里面定义的没有方法体的方法就是抽象方法,在方法声明的时候没有大括号以及其中的内容,另外在声明...

PHP中函数rand和mt_rand的区别比较

PHP函数rand和mt_rand    mt_rand() 比rand() 快四倍      很多老的 libc 的随机数发生器具有一些不确定和未知的特性而且很慢。PHP 的 rand...

PHP正则过滤处理微信昵称中emoji字符的方法

本文实例讲述了PHP正则过滤处理微信昵称中emoji字符的方法。分享给大家供大家参考,具体如下: 今天刚做了一个微信应用,在获取微信昵称的过程中报错了,经查原因是微信昵称中包含emoji...

PHP函数shuffle()取数组若干个随机元素的方法分析

本文实例讲述了PHP函数shuffle()取数组若干个随机元素的方法。分享给大家供大家参考,具体如下: 有时候我们需要取数组中若干个随机元素(比如做随机推荐功能),那么PHP要如何实现呢...

数组与类使用PHP的可变变量名需要的注意的问题

有时候可变的变量名会给编程带来很大的方便。也就是说变量名可以被动态的命名和使用。通常变量通过下面这样的语句来命名 :$a = 'hello';可变变量名指的是使用一个变量的值作为这个变量...