0

0

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

php中文网

php中文网

发布时间:2016-07-25 09:12:15

|

1984人浏览过

|

来源于php中文网

原创

长微博图片生成(可包含图片,初步设置只允许前两张图片,另外本方法图片排版比较麻烦,故暂设置两张图片)
简单的文本生成图片较为简单,但是如果需要富文本则相对比较麻烦,当然也有一些成型的源码,不过有些需要安装组件(一定的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
  137. if($start==0 && $str[$i]==">"){
  138. $start = 1;
  139. }elseif($start==1){
  140. if($str[$i]=="
  141. $start = 0;
  142. $alltext .= " ";
  143. }elseif(ord($str[$i])>31){
  144. $alltext .= $str[$i];
  145. }
  146. }
  147. }
  148. $alltext = str_replace(" "," ",$alltext);
  149. $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
  150. $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  151. return $alltext;
  152. }
  153. /**
  154. *
  155. * 自动换行处理
  156. * @param unknown_type $fontsize字体大小
  157. * @param unknown_type $angle角度
  158. * @param unknown_type $fontface字体名称(最好使用绝对路径)
  159. * @param unknown_type $string字符串
  160. * @param unknown_type $width预设宽度
  161. */
  162. function autowrap($fontsize, $angle, $fontface, $string, $width) {
  163. $content = "";
  164. $letter = array();
  165. // 将字符串拆分成一个个单字 保存到数组 letter 中
  166. for ($i=0;$i
  167. $letter[] = mb_substr($string, $i, 1);
  168. }
  169. foreach ($letter as $l) {
  170. $teststr = $content." ".$l;
  171. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  172. // 判断拼接后的字符串是否超过预设的宽度
  173. if (($testbox[2] > $width) && ($content !== "")) {
  174. $content .= "\n";
  175. }
  176. $content .= $l;
  177. }
  178. return $content;
  179. }
  180. /**
  181. *
  182. * 获取一定文字换行后的行数(高度)
  183. * @param unknown_type $fontsize字体大小
  184. * @param unknown_type $angle角度
  185. * @param unknown_type $fontface字体名称(最好使用绝对路径)
  186. * @param unknown_type $string字符串
  187. * @param unknown_type $width预设宽度
  188. */
  189. function get_wrap_height($fontsize, $angle, $fontface, $string, $width) {
  190. $content = "";
  191. $rows_count = 0;
  192. $letter = array();
  193. // 将字符串拆分成一个个单字 保存到数组 letter 中
  194. for ($i=0;$i
  195. $letter[] = mb_substr($string, $i, 1);
  196. }
  197. foreach ($letter as $l) {
  198. $teststr = $content." ".$l;
  199. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  200. // 判断拼接后的字符串是否超过预设的宽度
  201. if (($testbox[2] > $width) && ($content !== "")) {
  202. $content .= "\n";
  203. $rows_count += 1;
  204. }else{
  205. $rows_count += 1/$width;
  206. }
  207. $content .= $l;
  208. }
  209. return $rows_count;
  210. }
  211. /**
  212. *
  213. * 替换函数(替换一次)
  214. * @param unknown_type $needle
  215. * @param unknown_type $replace
  216. * @param unknown_type $haystack
  217. */
  218. function str_replace_once($needle, $replace, $haystack) {
  219. $pos = strpos($haystack, $needle);
  220. if ($pos === false) {
  221. return $haystack;
  222. }
  223. return substr_replace($haystack, $replace, $pos, strlen($needle));
  224. }
  225. ?>
复制代码


热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

616

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

194

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

91

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

20

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

54

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

29

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

15

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

598

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

56

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
极致CMS零基础建站教学视频
极致CMS零基础建站教学视频

共62课时 | 5.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号