首页 后端开发 php教程 长微博图片生成(可包含图片)

长微博图片生成(可包含图片)

Jul 25, 2016 am 09:12 AM

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


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在Laravel中使用Flash会话数据 在Laravel中使用Flash会话数据 Mar 12, 2025 pm 05:08 PM

Laravel使用其直观的闪存方法简化了处理临时会话数据。这非常适合在您的应用程序中显示简短的消息,警报或通知。 默认情况下,数据仅针对后续请求: $请求 -

php中的卷曲:如何在REST API中使用PHP卷曲扩展 php中的卷曲:如何在REST API中使用PHP卷曲扩展 Mar 14, 2025 am 11:42 AM

PHP客户端URL(curl)扩展是开发人员的强大工具,可以与远程服务器和REST API无缝交互。通过利用Libcurl(备受尊敬的多协议文件传输库),PHP curl促进了有效的执行

简化的HTTP响应在Laravel测试中模拟了 简化的HTTP响应在Laravel测试中模拟了 Mar 12, 2025 pm 05:09 PM

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显着减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

在Codecanyon上的12个最佳PHP聊天脚本 在Codecanyon上的12个最佳PHP聊天脚本 Mar 13, 2025 pm 12:08 PM

您是否想为客户最紧迫的问题提供实时的即时解决方案? 实时聊天使您可以与客户进行实时对话,并立即解决他们的问题。它允许您为您的自定义提供更快的服务

解释PHP中晚期静态结合的概念。 解释PHP中晚期静态结合的概念。 Mar 21, 2025 pm 01:33 PM

文章讨论了PHP 5.3中引入的PHP中的晚期静态结合(LSB),从而允许静态方法的运行时分辨率调用以获得更灵活的继承。 LSB的实用应用和潜在的触摸

自定义/扩展框架:如何添加自定义功能。 自定义/扩展框架:如何添加自定义功能。 Mar 28, 2025 pm 05:12 PM

本文讨论了将自定义功能添加到框架上,专注于理解体系结构,识别扩展点以及集成和调试的最佳实践。

框架安全功能:防止漏洞。 框架安全功能:防止漏洞。 Mar 28, 2025 pm 05:11 PM

文章讨论了框架中的基本安全功能,以防止漏洞,包括输入验证,身份验证和常规更新。

See all articles