张新全
在我们写cms网站程序或者二次开发的时候,如果你没有上传缩略图,将文章中的第一张作为自己的缩略图,使我们程序员最常用的手段,今天分享给大家如何用Thinkphp框架,将文章获取第一张图片为缩略图实现方法
张新全
原理:通过正则匹配图片地址获取第一张图片地址
此为函数在模块或是全局Common文件夹中的function.php中
/**
* [getPic description]
* 获取文本中首张图片地址
* @param [type] $content [description]
* @return [type] [description]
*/
function getPic($content){
if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
$str=$matches[3][0];
if (preg_match('/\/Uploads\/images/', $str)) {
return $str1=substr($str,7);
}
}
}
张新全
用法演示
$content=I('post.body');//获取富文本编辑器内容
$info=getPic($content);//使用函数 返回匹配地址 如果不为空则声称缩略图
if(!$info==null){
$thumb=$info.'thumb240x160.png';
$image = new \Think\Image();//实例化图像处理,缩略图功能
$image->open($info);// 生成一个居中裁剪为240*160的缩略图
$unlink=$image->thumb(240, 160,\Think\Image::IMAGE_THUMB_CENTER)->save($thumb);
}else{
$thumb='';
}