搜尋
首頁後端開發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("/長微博圖片生成(可包含圖片)]*]*)"[^>]* >/", $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 "pnggif($image);
  34. break;
  35. case "pnggif ":
  36. $im = imagecreatefrompng($image);
  37. break;
  38. case "jpeg":
  39. $im = imagecreatefromjpeg($image);
  40. break;
  41. case "jpg ":
  42. $im = imagecreatefromjpeg($image);
  43. break;
  44. }
  45. $imgs[$i] = array(
  46. '0'=>$im,
  47. ' height'=>floor(410/imagesx($im)*imagesy($im)), //比例縮放
  48. );
  49. }
  50. $content = strip_tags($content,'長微博圖片生成(可包含圖片) ');
  51. foreach($m[0] as $i=>$full) {
  52. //$replace_con = str_repeat("n",ceil($imgs[$i]['height']/ 25));
  53. $content = str_replace_once($full, 'img-pos-pos'.$i,$content); //只替換一次,防止出現相同的
  54. //$img_pos[$i ] = mb_strpos($content, 'img-pos-pos'.$i); //使用去除img標籤後的文字
  55. //$imgs[$i]['img_pos'] = $img_pos[$i ];
  56. $imgs[$i]['f​​ull'] = $full;
  57. //$content = str_replace('img-pos-pos'.$i,$replace_con, $content);
  58. //$all_img_height += $imgs[$i]['height'];
  59. }
  60. $all_img_height += $imgs[0]['height'];
  61. $content = strip_tags($ content.'endendend');//防止新增的換行符號/空格刪除
  62. }
  63. $content = strip_tags($content);
  64. //$content = SpHtml2Text($content);//轉換為文字
  65. $content = autowrap(12, 0, $font, $content, 395); // 自動換行處理
  66. if(!empty($imgs)){
  67. foreach($imgs as $i=>$v){
  68. $replace_con = str_repeat("n",ceil($v['height']/25));
  69. $img_pos[$i] = mb_strpos($content, ' img-pos-pos'.$i); //使用去除img標籤後的文字
  70. $imgs[$i]['img_pos'] = $img_pos[$i];
  71. $content = str_replace( 'img-pos-pos'.$i,$replace_con, $content); } }
  72. //$add_footer_input = "n自訂底部新增nnn";//自訂底部
  73. $input = str_replace("r", "", stripcslashes($content));
  74. //$ input = str_replace(" ", "", stripcslashes($input));
  75. //$title = explode("nn", $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'); imagecopymerge ( $img, $child2, 0, $height-215, 0, 0, imagesx ( $child2 ) , imagesy ( $child2 ), 100 );
  101. }
  102. //圖片加入(img標籤)
  103. if(!empty($imgs)){
  104. $before_img_height = 0;
  105. foreach($imgs as $i=>$v){
  106. $child = $v[0];
  107. $part_content = mb_substr($content,0,$v['img_pos'],'utf -8');
  108. $rows_count = get_wrap_height(12, 0, $font, $part_content , 300);
  109. $dst_y = ($rows_count+7)*27 - 9 + $before_img_height; before_img_height += $v['height'] + 25;//累積佔用高度
  110. imagecopyresampled($img,$child,18,$dst_y,0,0,'410',$v['height'], imagesx($child),imagesy($child));
  111. }
  112. }
  113. //產生圖片回傳圖片連結
  114. $file = empty($img_path)?'img/p -' . $pid . '.png':$img_path.'/p-'.$pid.'.png';
  115. imagepng($img, $file);
  116. imagedestroy($img);
  117. if(empty($img_path_url)){
  118. return 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $file;
  119. }else{
  120. return 'http://' . $_SERVER['HTTP_HOST'] . $img_path_url . '/p-'.$pid.'.png';
  121. }
  122. }
  123. /**
  124. * html轉換為text
  125. * @param inputString
  126. * @return
  127. */
  128. function SpHtml2Text($str){
  129. //$str = strip_tags($str);
  130. $str = preg_replace("/||/isU","n",$str);
  131. $alltext = "";
  132. $start = 1;
  133. for($i=0;$i if($start==0 && $str[$i]== ">"){
  134. $start = 1;
  135. }elseif($start==1){
  136. if($str[$i]==" $start = 0;
  137. $alltext .= " ";
  138. }elseif(ord($str[$i])>31){
  139. $alltext .= $str[$i];
  140. }
  141. }
  142. }
  143. $alltext = str_replace(" "," ",$alltext);
  144. $alltext = preg_replace("/&([^;&]*)(;|&)/ ","",$alltext);
  145. $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  146. return $alltext;
  147. }
  148. /**
  149. *
  150. * 自動換行處理
  151. * @param unknown_type $fontsize字體大小
  152. * @param unknown_type $angle角度
  153. * @param unknown_type $fontface(最好使用絕對路徑字體名稱(最好使用絕對路徑)(face
  154. * @param unknown_type $string字串
  155. * @param unknown_type $width預設寬度
  156. */
  157. function autowrap($fontsize, $angle, $fontface, $string, $width) {
  158. $content = "";
  159. $letter = array();
  160. // 將字串拆分成一個單字儲存到陣列letter 中
  161. for ($i=0;$i $letter[] = mb_substr ($string, $i, 1);
  162. }
  163. foreach ($letter as $l) {
  164. $teststr = $content." ".$l;
  165. $testbox = imagettfbbox($ fontsize, $angle, $fontface, $teststr);
  166. // 判斷拼接後的字串是否超過預設的寬度
  167. if (($testbox[2] > $width) && ($content != = "")) {
  168. $content .= "n";
  169. }
  170. $content .= $l;
  171. }
  172. return $content;
  173. }
  174. /**
  175. *
  176. * 取得某一文字換行後的行數(高度)
  177. * @param unknown_type $fontsize字體大小
  178. * @param unknown_type $angle角度
  179. * @param unknown_type $unknown_type名稱(最好使用絕對路徑)
  180. * @param unknown_type $string字串
  181. * @param unknown_type $width預設寬度
  182. */
  183. function get_wrap_height($fontsize, $angle, $fontface, $string, $width) {
  184. $content = "";
  185. $rows_count = 0;
  186. $letter = array();
  187. // 將字串拆分成一個單字儲存到陣列letter 中
  188. for ($i=0;$i $letter[] = mb_substr($string, $i, 1);
  189. }
  190. foreach ($letter as $l) {
  191. $teststr = $content." ".$l;
  192. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  193. // 判斷拼接後的字串是否超過預設的寬度
  194. if (($ testbox[2] > $width) && ($content !== "")) {
  195. $content .= "n";
  196. $rows_count += 1;
  197. }else{
  198. $ rows_count += 1/$width;
  199. }
  200. $content .= $l;
  201. }
  202. return $rows_count;
  203. }
  204. /**
  205. *
  206. * 替換函數(替換一次)
  207. * @param unknown_type $needle
  208. * @param unknown_type $replace
  209. * @param unknown_type $haystack
  210. */
  211. */
  212. function str_replace_once($needle, $replace, $haystack) {
  213. $pos = strpos($haystack, $needle);
  214. if ($pos === false) {
  215. return $haystack;
  216. }
  217. return substr_replace($haystack, $replace, $pos, strlen($needle));
  218. }
?>
複製程式碼
?>
複製程式碼?>
複製程式碼
?>

複製程式碼?>複製碼>
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
繼續使用PHP:耐力的原因繼續使用PHP:耐力的原因Apr 19, 2025 am 12:23 AM

PHP仍然流行的原因是其易用性、靈活性和強大的生態系統。 1)易用性和簡單語法使其成為初學者的首選。 2)與web開發緊密結合,處理HTTP請求和數據庫交互出色。 3)龐大的生態系統提供了豐富的工具和庫。 4)活躍的社區和開源性質使其適應新需求和技術趨勢。

PHP和Python:探索他們的相似性和差異PHP和Python:探索他們的相似性和差異Apr 19, 2025 am 12:21 AM

PHP和Python都是高層次的編程語言,廣泛應用於Web開發、數據處理和自動化任務。 1.PHP常用於構建動態網站和內容管理系統,而Python常用於構建Web框架和數據科學。 2.PHP使用echo輸出內容,Python使用print。 3.兩者都支持面向對象編程,但語法和關鍵字不同。 4.PHP支持弱類型轉換,Python則更嚴格。 5.PHP性能優化包括使用OPcache和異步編程,Python則使用cProfile和異步編程。

PHP和Python:解釋了不同的範例PHP和Python:解釋了不同的範例Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python:深入了解他們的歷史PHP和Python:深入了解他們的歷史Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

在PHP和Python之間進行選擇:指南在PHP和Python之間進行選擇:指南Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和框架:現代化語言PHP和框架:現代化語言Apr 18, 2025 am 12:14 AM

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的影響:網絡開發及以後PHP的影響:網絡開發及以後Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

See all articles

熱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 無盡。

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器