ホームページ バックエンド開発 PHPチュートリアル 長い Weibo 写真の生成 (写真を含めることができます)

長い Weibo 写真の生成 (写真を含めることができます)

Jul 25, 2016 am 09:12 AM

長文Weibo画像生成(画像を含めることができ、初期設定では最初の2枚のみ許可されています。また、この方法は画像のフォーマットが面倒なので、一時的に2枚の画像を設定します)
単純なテキストから画像を生成するのは比較的簡単です、ただし、リッチテキストが必要な場合は、比較的面倒です。もちろん、いくつかのソースコードが形成されていますが、コンポーネントのインストールが必要なものもあります(特定のWeb環境)。また、オープンソースのpaintyが良いようです。ここでは、p タグと img タグの画像生成を自分で実装していますが、これにも少し時間がかかります (主に画像のレイアウトに)。この機能はもともと WordPress で長い Weibo 投稿をプッシュするために使用され、コミュニケーションと学習のための機能にカプセル化されました。
  1. <?php
  2. /**
  3. *
  4. * 長い Weibo 画像生成
  5. * @paramknown_type 記事 ID
  6. * @paramknown_type 記事コンテンツ (ID に従って取得でき、ここに値を直接渡します)
  7. * @paramknown_type $img_path 画像を保存するためのハード パス
  8. * @paramknown_type $img_path_url画像パスURL
  9. */
  10. function weibo_img_create($article_id,$text,$title='',$img_path='',$img_path_url=''){
  11. $font = dirname(__FILE__)."/droid.ttf";
  12. $pid = $article_id;
  13. //分割された p タグの処理
  14. $p_count = substr_count($text,'</p>') //分割されたタグ番号
  15. ; $content = preg_replace("/</p>/isU","n",$text); //分割ラベル
  16. //画像画像ラベル処理
  17. $all_img_height = 0;
  18. if(preg_match_all( "/< img[^>]*src="([^"]*)"[^>]*>/", $content, $m)) {
  19. //最初の 2 枚の写真のみを撮影します
  20. $m[ 0] = array_slice($m[0],0,2);
  21. $m[1] = array_slice($m[1],0,2);
  22. //画像リソースを保存
  23. foreach($ m[1] as $i=>$src) {
  24. $imgs[] = $src;
  25. }
  26. //すべての画像を取得
  27. foreach($imgs as $i=>$image) {
  28. $ext = end(explode( ".", $image));
  29. $im = null;
  30. switch($ext) {
  31. case "gif":
  32. $im = imagecreatefromgif($image);
  33. Break;
  34. case "png" :
  35. $im = imagecreatefrompng($image);
  36. ブレーク;
  37. case "jpeg":
  38. $im = imagecreatefromjpeg($image);
  39. ブレーク;
  40. case "jpg":
  41. $im = imagecreatefromjpeg($image);
  42. ブレーク;
  43. }
  44. $imgs[$i] = array(
  45. '0'=>$im,
  46. 'height'=>floor(410/imagesx($im)*imagesy($im)), // 比例して拡大縮小します
  47. ) ;
  48. }
  49. $content =strip_tags($content,'<img>');
  50. foreach($m[0] as $i=>$full) {
  51. //$replace_con = str_repeat ("n", ceil($imgs[$i]['height']/25));
  52. $content = str_replace_once($full, 'img-pos-pos'.$i,$content); //同じ
  53. //$img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //img タグを削除したテキストを使用します
  54. //$imgs[$ i]['img_pos '] = $img_pos[$i];
  55. $imgs[$i]['f​​ull'] = $full;
  56. //$content = str_replace('img-pos-pos'.$i, $replace_con, $content );
  57. //$all_img_height += $imgs[$i]['height'];
  58. }
  59. $all_img_height += $imgs[0]['height'];
  60. $content =strip_tags( $content.'endendend ');//追加された改行/スペースが削除されないようにします
  61. }
  62. $content =strip_tags($content);
  63. //$content = SpHtml2Text($content);//テキストに変換します
  64. $ content = autowrap(12 , 0, $font, $content, 395); // 自動行折り返し
  65. if(!empty($imgs)){
  66. foreach($imgs as $i=>$v){
  67. $ replace_con = str_repeat(" n",ceil($v['height']/25));
  68. $img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //imgタグを削除した後にテキストを使用
  69. $imgs[$i]['img_pos'] = $img_pos[$i];
  70. $content = str_replace('img-pos-pos'.$i,$replace_con, $content);
  71. //$add_footer_input = "nカスタムボトム追加nnn";//カスタムボトム
  72. $input = str_replace("r", "",stripcslashes($content));
  73. //$input = str_replace(" " , "" 、stripcslashes($input));
  74. //$title =explode("nn", $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. $bgcolor = imagecolorallocate($img, ' 250', '250', '250') ;
  83. $bdcolor = imagecolorallocate($img, '250', '250', '250');
  84. $color = imagecolorallocate($img, '0', '0' , '0');
  85. $color_title = imagecolorallocate ($img, '250', '140', '0');
  86. $input = str_replace('endendend','',$input); //追加されたものを削除します。干渉文字
  87. imagettftext($img, 12, 0 , 20, 160, $color, $font, $input);
  88. imagettftext($img, 18, 0, 21, 160, $color_title, $font, $title);
  89. imagerectangle($img, 0, 0, imagex ($img) - 1, imagesy($img) - 1, $bdcolor);
  90. //ここでアイコンの保存パスを設定します
  91. $img_path = dirname(__FILE__).' /../../weibo_img';
  92. $ img_path_url = '/wp-content/weibo_img';
  93. //$img_path = empty($img_path)?'':$img_path;
  94. //$img_path_url = empty( $img_path_url)?'':$img_path_url;
  95. //公開ヘッダー/ボトム画像を合成します
  96. if(file_exists($img_path.'/weibo_header.jpg') && file_exists($img_path.'/weibo_footer.jpg')){
  97. $child1 = imagecreatefromjpeg($img_path.'/weibo_header.jpg');
  98. $child2 = imagecreatefromjpeg($img_path.'/weibo_footer.jpg');
  99. imagecopymerge ( $img, $child1, 0, 40, 0, 0 、imagesx ( $child1 )、imagesy ( $child1 )、100 );
  100. 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;
  110. $before_img_height += $v['height'] + 25;//累積占有高さ
  111. imagecopyresampled($img,$child,18,$ dst_y,0,0,'410',$ v['height'],imagesx($child),imagesy($child));
  112. }
  113. }
  114. //画像を生成して画像リンクを返す
  115. $file = empty ($img_path)?'img/p-' . $pid . '.png':$img_path.'/p-'.$pid.'.png';
  116. imagepng($img, $file);
  117. imagedestroy( $img);
  118. if(empty($img_path_url) ){
  119. 'http://' . $_SERVER['REQUEST_URI'] . $file;
  120. }else{
  121. return 'http://' . $_SERVER['HTTP_HOST'] . $img_path_url . '/p-'.$pid.'.png';
  122. }
  123. }
  124. /**
  125. * HTML をテキストに変換します
  126. * @param inputString
  127. * @return
  128. * /
  129. function SpHtml2Text($str){
  130. // $str =strip_tags($str);
  131. $str = preg_replace("/<sty(.*)\/style>|<scr(.*)\/ script>|<!--(.*) -->/isU","n",$str);
  132. $alltext = "";
  133. $start = 1;
  134. for($i=0;$ i<strlen($str);$i++){
  135. if($start==0 && $str[$i]==">"){
  136. $start = 1;
  137. }elseif($start==1 ){
  138. if($str[$i]= ="<"){
  139. $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. * @paramunknown_type $fontsize フォントサイズ
  155. * @paramunknown_type $angle 角度
  156. * @paramunknown_type $fontface フォント名 (できれば絶対パスを使用)
  157. * @paramunknown_type $string string
  158. * @paramknown_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. $content を返します;
  176. }
  177. /**
  178. *
  179. * 特定のテキストが折り返された後の行数(高さ)を取得します
  180. * @paramknown_type $fontsize フォントサイズ
  181. * @paramunknown_type $angle angle
  182. * @paramunknown_type $fontface フォント名 (を使用するのが最適です)絶対パス)
  183. * @paramknown_type $string string
  184. * @paramknown_type $widthDefault 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<mb_strlen($string);$i++) {
  192. $letter[] = mb_substr($string, $ i, 1);
  193. }
  194. foreach ($letter as $l) {
  195. $teststr = $content." ".$l;
  196. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr); // 結合された文字列がプリセット幅を超えているかどうかを判定します
  197. if (($testbox[2] > $width) && ($content !== "")) {
  198. $content .= "n"; $ rows_count += 1;
  199. }else{
  200. $rows_count += 1/$width;
  201. }
  202. $content .= $l;
  203. }
  204. return $rows_count;
  205. }
  206. /**
  207. *
  208. * 置換関数(1回置換)
  209. * @paramknown_type $needle
  210. * @paramunknown_type $replace
  211. * @paramunknown_type $haystack
  212. */
  213. 関数 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. ?>
コードをコピー
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットな記事タグ

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

11ベストPHP URLショートナースクリプト(無料およびプレミアム) 11ベストPHP URLショートナースクリプト(無料およびプレミアム) Mar 03, 2025 am 10:49 AM

11ベストPHP URLショートナースクリプト(無料およびプレミアム)

Instagram APIの紹介 Instagram APIの紹介 Mar 02, 2025 am 09:32 AM

Instagram APIの紹介

Laravelでフラッシュセッションデータを使用します Laravelでフラッシュセッションデータを使用します Mar 12, 2025 pm 05:08 PM

Laravelでフラッシュセッションデータを使用します

LaravelのバックエンドでReactアプリを構築する:パート2、React LaravelのバックエンドでReactアプリを構築する:パート2、React Mar 04, 2025 am 09:33 AM

LaravelのバックエンドでReactアプリを構築する:パート2、React

Laravelテストでの簡略化されたHTTP応答のモッキング Laravelテストでの簡略化されたHTTP応答のモッキング Mar 12, 2025 pm 05:09 PM

Laravelテストでの簡略化されたHTTP応答のモッキング

PHPのカール:REST APIでPHPカール拡張機能を使用する方法 PHPのカール:REST APIでPHPカール拡張機能を使用する方法 Mar 14, 2025 am 11:42 AM

PHPのカール:REST APIでPHPカール拡張機能を使用する方法

Codecanyonで12の最高のPHPチャットスクリプト Codecanyonで12の最高のPHPチャットスクリプト Mar 13, 2025 pm 12:08 PM

Codecanyonで12の最高のPHPチャットスクリプト

2025 PHP状況調査の発表 2025 PHP状況調査の発表 Mar 03, 2025 pm 04:20 PM

2025 PHP状況調査の発表

See all articles