基本流程:
1、获取目标网站图片地址。
2、读取图片内容。
3、创建要保存图片的路径并命名图片名称。
4、写入图片内容。
5、完成。
我们自定义几个函数,实现采集远程图片的功能。
1、make_dir()建立目录。判断要保存的图片文件目录是否存在,如果不存在则创建目录,并且将目录设置为可写权限。
2 | function make_dir( $path ){ |
3 | if (!<a href= "http://www.jbxue.com/zt/file_exists/" target= "_blank" class = "infotextkey" > file_exists </a>( $path )){//不存在则建立 |
4 | $mk =@ mkdir ( $path ,0777); |
2、read_filetext()取得图片内容。使用fopen打开图片文件,然后fread读取图片文件内容。
02 | function read_filetext( $filepath ){ |
03 | $filepath =trim( $filepath ); |
04 | $htmlfp =@ fopen ( $filepath , "r" ); |
06 | if ( strstr ( $filepath , "://" )){ |
07 | while ( $data =@ fread ( $htmlfp ,500000)){ |
13 | $string =@ fread ( $htmlfp ,@ filesize ( $filepath )); |
3、write_filetext()写文件,将图片内容fputs写入文件中,即保存图片文件。
2 | function write_filetext( $filepath , $string ){ |
4 | $fp =@ fopen ( $filepath , "w" ); |
4、get_filename()获取图片名称,也可以自定义要保存的文件名。
2 | function get_filename( $filepath ){ |
3 | $fr = explode ( "/" , $filepath ); |
5、在函数save_pic()中调用,最后返回保存后的图片路径。
02 | function save_pic( $url , $savepath = '' ){ |
05 | $url = str_replace ( " " , "%20" , $url ); |
07 | $string =read_filetext( $url ); |
12 | $filename = get_filename( $url ); |
16 | $filepath = $savepath . $filename ; |
18 | write_filetext( $filepath , $string ); |
21 | 调用save_pic()函数保存图片,测试代码: |
23 | $pic = "http://www.jbxue.com/1205/06/2776119_demo.jpg" ; |
25 | $savepath = "images/" ; |
26 | echo save_pic( $pic , $savepath ); |
实际应用中,可能会采集某个站点的内容,比如产品信息,包括采集防盗链的图片保存到网站上服务器上。
这时可以使用正则匹配页面内容,将页面中相匹配的图片都找出来,然后分别下载到网站服务器上,完成图片的采集。
测试代码:
02 | function get_pic( $cont , $path ){ |
03 | $pattern_src = '/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/' ; |
04 | $num = preg_match_all( $pattern_src , $cont , $match_src ); |
05 | $pic_arr = $match_src [1]; |
06 | foreach ( $pic_arr as $pic_item ) { |
07 | save_pic( $pic_item , $path ); |
14 | $url = "http://www.jbxue.com/321/3215791.html" ; |
15 | $content = <a href= "http://www.jbxue.com/zt/file_get_contents/" target= "_blank" class = "infotextkey" > file_get_contents </a>( $url );//获取网页内容 |
16 | $preg = '#<div class="art_con">(.*)<div class="ivy620 ivy620Ex"></div>#iUs' ; |
17 | preg_match_all( $preg , $content , $arr ); |
19 | get_pic( $cont , 'img/' ); |
以上代码经测试可以采集图片,但特殊情况下未测试,比如目标网站做了302多次跳转的,目标网站做了多种防采集的,留给大家自行测试与研究。