首页 > 技术文章 > Thinkphp发布文章获取第一张图片为缩略图实现方法

CHEUNGKAMING 2016-07-29 10:13 原文

正则匹配图片地址获取第一张图片地址

此为函数 在模块或是全局Common文件夹中的function.php中

 1 /**
 2  * [getPic description]
 3  * 获取文本中首张图片地址
 4  * @param  [type] $content [description]
 5  * @return [type]          [description]
 6  */
 7   function getPic($content){
 8         if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
 9            $str=$matches[3][0];
10        if (preg_match('/\/Uploads\/images/', $str)) {
11            return $str1=substr($str,7);
12        }
13     }
14 }

用法演示

 1   $content=I('post.body');//获取富文本编辑器内容
 2         $info=getPic($content);//使用函数 返回匹配地址 如果不为空则声称缩略图
 3         if(!$info==null){
 4             $thumb=$info.'thumb240x160.png';
 5             $image = new \Think\Image();//实例化图像处理,缩略图功能
 6             $image->open($info);// 生成一个居中裁剪为240*160的缩略图
 7             $unlink=$image->thumb(240, 160,\Think\Image::IMAGE_THUMB_CENTER)->save($thumb);
 8         }else{
 9             $thumb='';
10         }
11  

 

推荐阅读