在开发中会需要摘取文章部分内容,生成卡片或者明信片之内的功能。生成一张图片便于传播与分享。

这里是我结合thinkphp写的生成卡片的功能,不是很完美但是很实用。

效果如下:

topic.jpg

php代码:

/**生成话题图片 
 * @param $filename 生成的文件名
 * @param $source   合并的头部大图
 * @param $title    标题
 * @param $intro    简介
 * @param $nickname 昵称
 * @return mixed
 */


function shareimg($filename,$source,$title,$intro,$nickname){
   $filethumb = str_replace('.jpg','_thumb.jpg',$filename);
   $filewater = str_replace('.jpg','_water.jpg',$filename);
   // 等比例缩放
   $image = new \Think\Image();
   $image->open($source);
   $image->thumb(750, 424)->save($filethumb);
   //$image->thumb(400, 290)->save($filethumb);
   // 获取实际高度 计算 离顶部的位置
   $height = $image->height();
   $title_h = 910;
   $fuhao_h = 450;
   $desc_h  = 500;

   // 添加头部背景
   $image->open('./blank.jpg')->water($filethumb,1)->save($filewater);

   $title = strip_tags($title);
   $title_len = mb_strlen($title,'utf-8');
   if($title_len > 15){
      $title = mb_substr($title,0,30,'utf-8');
      $txt = '';
      for($i=0;$i<2;$i++){
         $offset_h = $title_h + 50*$i;
         $txt = mb_substr($title,$i*15,15,'utf-8');
         $image->open($filewater)->text($txt,'./fzltxh.ttf',30,'#000',1,array(60,$offset_h),0)->save($filewater);
      }
   }else{
      // 添加标题
      $image->open($filewater)->text($title,'./fzltxh.ttf',40,'#000',1,array(60,$title_h),0)->save($filewater);
   }
   // 添加符号
   $image->open($filewater)->text('“','./fzltxh.ttf',60,'#000',1,array(-40,$fuhao_h),0)->save($filewater);
   //添加描述
   $intro = strip_tags($intro);
   $len = mb_strlen($intro,'utf-8');
   if($len>80){
      $intro = mb_substr($intro,0,77,'utf-8').'...';
   }
   if($len<=14){
      $image->open($filewater)->text($intro,'./fzltxh.ttf',26,'#666666',1,array(60,$desc_h),0)->save($filewater);
   }else{
      $txt = '';
      for($i=0;$i<5;$i++){
         $offset_h = $desc_h + 60*$i;
         $txt = mb_substr($intro,$i*18,18,'utf-8');
         $image->open($filewater)->text($txt,'./fzltxh.ttf',26,'#666666',1,array(60,$offset_h),0)->save($filewater);
      }
   }
   $nickname = '— '.strip_tags($nickname);
   $image->open($filewater)->text($nickname,'./fzltxh.ttf',28,'#333333',6,array(-60,250),0)->save($filename);
   unlink($filethumb);
   unlink($filewater);
   return $filename;
}

注意:

这里会有个问题,就是当内容都是字母或者数字的时候,就会出现计算字符长度在写入到图片中很大的空隙。


相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!