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

yipeiwu_com6年前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中isset与array_key_exists的区别实例分析

本文实例讲述了PHP中isset与array_key_exists的区别。分享给大家供大家参考。具体分析如下: 1.对于数组值的判断不同,对于值为null或''或false,isset返...

PHP合并数组的2种方法小结

前言 在此前合并数组我一直用的是array_merge()这个函数,但最近我在换工作的时候遇到一道合并数组的面试题,我当时想的是将两个数组先转化为字符串,合并后再转化为数组输出,面试官说...

常用的php对象类型判断

<HTML> <HEAD> <TITLE>php常用的数值判断函数</TITLE> </HEAD> <BODY>...

PHP sleep()函数, usleep()函数

PHP sleep() 函数 定义和用法 sleep() 函数延迟代码执行若干秒。 语法sleep(seconds) seconds 必需。以秒计的暂停时间。 返回值 若成功,返回 0...

PHP转盘抽奖接口实例

本文实例讲述了PHP转盘抽奖接口的实现方法。分享给大家供大家参考。具体如下: 这里的转盘抽奖随机返回一个转盘角度,概率可自己定义 lottery_get.php接口文件如下: 复制代码...