长微博图片生成(可包含图片,初步设置只允许前两张图片,另外本方法图片排版比较麻烦,故暂设置两张图片)
简单的文本生成图片较为简单,但是如果需要富文本则相对比较麻烦,当然也有一些成型的源码,不过有些需要安装组件(一定的web环境),另外开源的painty似乎也不错,可以参考,这里只是自己实现p、img两个标签的图片生成,也花了一点时间(主要还是图片排版方面)
本功能本来是做wordpress的长微博推送,封装成函数供交流学习
  1. *
  2. * 长微博图片生成
  3. * @param unknown_type 文章id
  4. * @param unknown_type 文章内容(可根据id获取,这里直接传值)
  5. * @param unknown_type $img_path图片保存硬路径
  6. * @param unknown_type $img_path_url图片路径url
  7. */
  8. function weibo_img_create($article_id,$text,$title='',$img_path='',$img_path_url=''){
  9. $font = dirname(__FILE__)."/droid.ttf";
  10. $pid = $article_id;
  11. //分段p标签处理
  12. $p_count = substr_count($text,'

    '); //分段标签个数
  13. $content = preg_replace("//isU","\n",$text); //分段标签
  14. //图片img标签处理
  15. $all_img_height = 0;
  16. if(preg_match_all("/]*src=\"([^\"]*)\"[^>]*>/", $content, $m)) {
  17. //只取前两张图片
  18. $m[0] = array_slice($m[0],0,2);
  19. $m[1] = array_slice($m[1],0,2);
  20. //保存图片资源
  21. foreach($m[1] as $i=>$src) {
  22. $imgs[] = $src;
  23. }
  24. //获取所有图片
  25. foreach($imgs as $i=>$image) {
  26. $ext = end(explode(".", $image));
  27. $im = null;
  28. switch($ext) {
  29. case "gif":
  30. $im = imagecreatefromgif($image);
  31. break;
  32. case "png":
  33. $im = imagecreatefrompng($image);
  34. break;
  35. case "jpeg":
  36. $im = imagecreatefromjpeg($image);
  37. break;
  38. case "jpg":
  39. $im = imagecreatefromjpeg($image);
  40. break;
  41. }
  42. $imgs[$i] = array(
  43. '0'=>$im,
  44. 'height'=>floor(410/imagesx($im)*imagesy($im)), //按比例缩放
  45. );
  46. }
  47. $content = strip_tags($content,'');
  48. foreach($m[0] as $i=>$full) {
  49. //$replace_con = str_repeat("\n",ceil($imgs[$i]['height']/25));
  50. $content = str_replace_once($full, 'img-pos-pos'.$i,$content); //只替换一次,防止出现相同的
  51. //$img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //使用去除img标签后的文本
  52. //$imgs[$i]['img_pos'] = $img_pos[$i];
  53. $imgs[$i]['full'] = $full;
  54. //$content = str_replace('img-pos-pos'.$i,$replace_con, $content);
  55. //$all_img_height += $imgs[$i]['height'];
  56. }
  57. $all_img_height += $imgs[0]['height'];
  58. $content = strip_tags($content.'endendend');//防止添加的换行符/空格被删除
  59. }
  60. $content = strip_tags($content);
  61. //$content = SpHtml2Text($content);//转化为文本
  62. $content = autowrap(12, 0, $font, $content, 395); // 自动换行处理
  63. if(!empty($imgs)){
  64. foreach($imgs as $i=>$v){
  65. $replace_con = str_repeat("\n",ceil($v['height']/25));
  66. $img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //使用去除img标签后的文本
  67. $imgs[$i]['img_pos'] = $img_pos[$i];
  68. $content = str_replace('img-pos-pos'.$i,$replace_con, $content);
  69. }
  70. }
  71. //$add_footer_input = "\n自定义底部添加\n\n\n";//自定义底部
  72. $input = str_replace("\r", "", stripcslashes($content));
  73. //$input = str_replace(" ", "", stripcslashes($input));
  74. //$title = explode("\n\n", $input);
  75. $ary = imagettfbbox (12, 0, $font, $input);
  76. $width = abs($ary[2] - $ary[0]) + 40;
  77. $height = abs($ary[1] - $ary[7]) + 220 + 215 + $p_count*25;
  78. //高清图片代替imagecreate(),若内容无图片建议使用imagecreate
  79. $img = @imagecreatetruecolor($width, $height);
  80. $bg_color=imagecolorallocate($img,229,231,230);
  81. imagecolortransparent($img,$bg_color); // 设置为透明色,若注释掉该行则输出上面设置的背景
  82. imagefill($img,0,0,$bg_color);
  83. $bgcolor = imagecolorallocate($img, '250', '250', '250');
  84. $bdcolor = imagecolorallocate($img, '250', '250', '250');
  85. $color = imagecolorallocate($img, '0', '0', '0');
  86. $color_title = imagecolorallocate($img, '250', '140', '0');
  87. $input = str_replace('endendend','',$input); //去除添加的干扰符
  88. imagettftext($img, 12, 0, 20, 160, $color, $font, $input);
  89. imagettftext($img, 18, 0, 21, 160, $color_title, $font, $title);
  90. imagerectangle($img, 0, 0, imagesx($img) - 1, imagesy($img) - 1, $bdcolor);
  91. //这里配置图标保存路径
  92. $img_path = dirname(__FILE__).'/../../weibo_img';
  93. $img_path_url = '/wp-content/weibo_img';
  94. //$img_path = empty($img_path)?'':$img_path;
  95. //$img_path_url = empty($img_path_url)?'':$img_path_url;
  96. //合成公共头部/底部图片
  97. if(file_exists($img_path.'/weibo_header.jpg') && file_exists($img_path.'/weibo_footer.jpg')){
  98. $child1 = imagecreatefromjpeg($img_path.'/weibo_header.jpg');
  99. $child2 = imagecreatefromjpeg($img_path.'/weibo_footer.jpg');
  100. imagecopymerge ( $img, $child1, 0, 40, 0, 0, imagesx ( $child1 ), imagesy ( $child1 ), 100 );
  101. imagecopymerge ( $img, $child2, 0, $height-215, 0, 0, imagesx ( $child2 ), imagesy ( $child2 ), 100 );
  102. }
  103. //图片加入(img标签)
  104. if(!empty($imgs)){
  105. $before_img_height = 0;
  106. foreach($imgs as $i=>$v){
  107. $child = $v[0];
  108. $part_content = mb_substr($content,0,$v['img_pos'],'utf-8');
  109. $rows_count = get_wrap_height(12, 0, $font, $part_content , 300);
  110. $dst_y = ($rows_count+7)*27 - 9 + $before_img_height;
  111. $before_img_height += $v['height'] + 25;//累计占用高度
  112. imagecopyresampled($img,$child,18,$dst_y,0,0,'410',$v['height'],imagesx($child),imagesy($child));
  113. }
  114. }
  115. //生成图片返回图片链接
  116. $file = empty($img_path)?'img/p-' . $pid . '.png':$img_path.'/p-'.$pid.'.png';
  117. imagepng($img, $file);
  118. imagedestroy($img);
  119. if(empty($img_path_url)){
  120. return 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $file;
  121. }else{
  122. return 'http://' . $_SERVER['HTTP_HOST'] . $img_path_url . '/p-'.$pid.'.png';
  123. }
  124. }
  125. /**
  126. * html转化为text
  127. * @param inputString
  128. * @return
  129. */
  130. function SpHtml2Text($str){
  131. //$str = strip_tags($str);
  132. $str = preg_replace("/||/isU","\n",$str);
  133. $alltext = "";
  134. $start = 1;
  135. for($i=0;$iif($start==0 && $str[$i]==">"){
  136. $start = 1;
  137. }elseif($start==1){
  138. if($str[$i]==" $start = 0;
  139. $alltext .= " ";
  140. }elseif(ord($str[$i])>31){
  141. $alltext .= $str[$i];
  142. }
  143. }
  144. }
  145. $alltext = str_replace(" "," ",$alltext);
  146. $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
  147. $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  148. return $alltext;
  149. }
  150. /**
  151. *
  152. * 自动换行处理
  153. * @param unknown_type $fontsize字体大小
  154. * @param unknown_type $angle角度
  155. * @param unknown_type $fontface字体名称(最好使用绝对路径)
  156. * @param unknown_type $string字符串
  157. * @param unknown_type $width预设宽度
  158. */
  159. function autowrap($fontsize, $angle, $fontface, $string, $width) {
  160. $content = "";
  161. $letter = array();
  162. // 将字符串拆分成一个个单字 保存到数组 letter 中
  163. for ($i=0;$i$letter[] = mb_substr($string, $i, 1);
  164. }
  165. foreach ($letter as $l) {
  166. $teststr = $content." ".$l;
  167. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  168. // 判断拼接后的字符串是否超过预设的宽度
  169. if (($testbox[2] > $width) && ($content !== "")) {
  170. $content .= "\n";
  171. }
  172. $content .= $l;
  173. }
  174. return $content;
  175. }
  176. /**
  177. *
  178. * 获取一定文字换行后的行数(高度)
  179. * @param unknown_type $fontsize字体大小
  180. * @param unknown_type $angle角度
  181. * @param unknown_type $fontface字体名称(最好使用绝对路径)
  182. * @param unknown_type $string字符串
  183. * @param unknown_type $width预设宽度
  184. */
  185. function get_wrap_height($fontsize, $angle, $fontface, $string, $width) {
  186. $content = "";
  187. $rows_count = 0;
  188. $letter = array();
  189. // 将字符串拆分成一个个单字 保存到数组 letter 中
  190. for ($i=0;$i$letter[] = mb_substr($string, $i, 1);
  191. }
  192. foreach ($letter as $l) {
  193. $teststr = $content." ".$l;
  194. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  195. // 判断拼接后的字符串是否超过预设的宽度
  196. if (($testbox[2] > $width) && ($content !== "")) {
  197. $content .= "\n";
  198. $rows_count += 1;
  199. }else{
  200. $rows_count += 1/$width;
  201. }
  202. $content .= $l;
  203. }
  204. return $rows_count;
  205. }
  206. /**
  207. *
  208. * 替换函数(替换一次)
  209. * @param unknown_type $needle
  210. * @param unknown_type $replace
  211. * @param unknown_type $haystack
  212. */
  213. function str_replace_once($needle, $replace, $haystack) {
  214. $pos = strpos($haystack, $needle);
  215. if ($pos === false) {
  216. return $haystack;
  217. }
  218. return substr_replace($haystack, $replace, $pos, strlen($needle));
  219. }
  220. ?>
复制代码


09-12 22:47