首頁 後端開發 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("/長微博圖片生成(可包含圖片)]*]*)"[^>]* >/", $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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話如何劫持工作,如何在PHP中減輕它? 會話如何劫持工作,如何在PHP中減輕它? Apr 06, 2025 am 12:02 AM

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

PHP 8.1中的枚舉(枚舉)是什麼? PHP 8.1中的枚舉(枚舉)是什麼? Apr 03, 2025 am 12:05 AM

PHP8.1中的枚舉功能通過定義命名常量增強了代碼的清晰度和類型安全性。 1)枚舉可以是整數、字符串或對象,提高了代碼可讀性和類型安全性。 2)枚舉基於類,支持面向對象特性,如遍歷和反射。 3)枚舉可用於比較和賦值,確保類型安全。 4)枚舉支持添加方法,實現複雜邏輯。 5)嚴格類型檢查和錯誤處理可避免常見錯誤。 6)枚舉減少魔法值,提升可維護性,但需注意性能優化。

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

什麼是REST API設計原理? 什麼是REST API設計原理? Apr 04, 2025 am 12:01 AM

RESTAPI設計原則包括資源定義、URI設計、HTTP方法使用、狀態碼使用、版本控制和HATEOAS。 1.資源應使用名詞表示並保持層次結構。 2.HTTP方法應符合其語義,如GET用於獲取資源。 3.狀態碼應正確使用,如404表示資源不存在。 4.版本控制可通過URI或頭部實現。 5.HATEOAS通過響應中的鏈接引導客戶端操作。

您如何在PHP中有效處理異常(嘗試,捕捉,最後,投擲)? 您如何在PHP中有效處理異常(嘗試,捕捉,最後,投擲)? Apr 05, 2025 am 12:03 AM

在PHP中,異常處理通過try,catch,finally,和throw關鍵字實現。 1)try塊包圍可能拋出異常的代碼;2)catch塊處理異常;3)finally塊確保代碼始終執行;4)throw用於手動拋出異常。這些機制幫助提升代碼的健壯性和可維護性。

PHP中的匿名類是什麼?您何時可以使用它們? PHP中的匿名類是什麼?您何時可以使用它們? Apr 04, 2025 am 12:02 AM

匿名類在PHP中的主要作用是創建一次性使用的對象。 1.匿名類允許在代碼中直接定義沒有名字的類,適用於臨時需求。 2.它們可以繼承類或實現接口,增加靈活性。 3.使用時需注意性能和代碼可讀性,避免重複定義相同的匿名類。

See all articles