Home Backend Development PHP Tutorial Long Weibo picture generation (can include pictures)

Long Weibo picture generation (can include pictures)

Jul 25, 2016 am 09:12 AM

Long Weibo image generation (can include images, the initial setting only allows the first two images. In addition, this method is more troublesome to format images, so two images are temporarily set)
It is relatively simple to generate images from simple text, but if rich text is required, it is relatively It is more troublesome. Of course, there are some formed source codes, but some require the installation of components (certain web environment). In addition, the open source painty seems to be good, you can refer to it. Here I just implement the image generation of p and img tags by myself, which also takes a lot of time. A little time (mainly for picture layout)
This function was originally used to push long Weibo posts in WordPress, and was encapsulated into functions for communication and learning.
  1. /**
  2. *
  3. * Long Weibo image generation
  4. * @param unknown_type article id
  5. * @param unknown_type article content (can be obtained according to the id, pass the value directly here)
  6. * @param unknown_type $img_path hard path for image saving
  7. * @param unknown_type $img_path_urlimage path 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. //Segmented p tag processing
  13. $p_count = substr_count($text,'

    '); //Segmented tag Number
  14. $content = preg_replace("/

    /isU","n",$text); //Segmentation label
  15. //Image img label processing
  16. $all_img_height = 0;
  17. if(preg_match_all( "/]*src="([^"]*)"[^>]*>/", $content, $m)) {
  18. //Only take the first two pictures
  19. $m[0] = array_slice($m[0],0,2);
  20. $m[1] = array_slice($m[1],0,2);
  21. //Save image resources
  22. foreach($ m[1] as $i=>$src) {
  23. $imgs[] = $src;
  24. }
  25. //Get all images
  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)), // Scale proportionally
  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); //only Replace once to prevent the same
  52. //$img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //Use the text after removing the img tag
  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');//Prevent added line breaks/spaces from being deleted
  60. }
  61. $content = strip_tags($content);
  62. //$content = SpHtml2Text($content);//Convert to text
  63. $ content = autowrap(12, 0, $font, $content, 395); // Automatic line wrapping
  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); //Use Text after removing img tag
  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 = "ncustom bottom add nnn";//custom bottom
  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. //High-definition picture instead imagecreate(), if the content does not have images, it is recommended to use imagecreate
  80. $img = @imagecreatetruecolor($width, $height);
  81. $bg_color=imagecolorallocate($img,229,231,230);
  82. imagecolortransparent($img,$bg_color); // Settings It is a transparent color. If this line is commented out, the background set above will be output
  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); //Remove the added interference characters
  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. //Configure the icon saving path here
  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. //Synthesize public header/bottom images
  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. //Image addition (img tag)
  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;//Cumulative occupied height
  113. imagecopyresampled($img,$child,18,$dst_y,0,0,'410',$ v['height'],imagesx($child),imagesy($child));
  114. }
  115. }
  116. //Generate image and return image link
  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. * Convert html to 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]= ="<"){
  140. $start = 0;
  141. $alltext .= " ";
  142. }elseif(ord($str[$i])>31){
  143. $alltext .= $str[$i] ;
  144. }
  145. }
  146. }
  147. $alltext = str_replace(" "," ",$alltext);
  148. $alltext = preg_replace("/&([^;&]*)(;|&)/","" ,$alltext);
  149. $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  150. return $alltext;
  151. }
  152. /**
  153. *
  154. * Automatic line wrapping processing
  155. * @param unknown_type $fontsize font size
  156. * @param unknown_type $angle angle
  157. * @param unknown_type $fontface font name (preferably use absolute path)
  158. * @param unknown_type $string string
  159. * @param unknown_type $widthDefault width
  160. */
  161. function autowrap($fontsize , $angle, $fontface, $string, $width) {
  162. $content = "";
  163. $letter = array();
  164. // Split the string into individual words and save them into the array letter
  165. for ($ i=0;$i $letter[] = mb_substr($string, $i, 1);
  166. }
  167. foreach ($letter as $l) {
  168. $teststr = $content." ".$l;
  169. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  170. // Determine whether the spliced ​​string exceeds the preset width
  171. if (($testbox[ 2] > $width) && ($content !== "")) {
  172. $content .= "n";
  173. }
  174. $content .= $l;
  175. }
  176. return $content;
  177. }
  178. /**
  179. *
  180. * Get the number of lines (height) after a certain text is wrapped
  181. * @param unknown_type $fontsize font size
  182. * @param unknown_type $angle angle
  183. * @param unknown_type $fontface font name (it is best to use absolute paths)
  184. * @param unknown_type $string string
  185. * @param unknown_type $widthDefault width
  186. */
  187. function get_wrap_height($fontsize, $angle, $fontface, $string, $width) {
  188. $content = "";
  189. $rows_count = 0;
  190. $letter = array() ;
  191. // Split the string into individual words and save them in the array letter
  192. for ($i=0;$i $letter[] = mb_substr($string, $i, 1);
  193. }
  194. foreach ($letter as $l) {
  195. $teststr = $content." ".$l;
  196. $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
  197. // Determine whether the spliced ​​string exceeds the preset width
  198. if (($testbox[2] > $width) && ($content !== "")) {
  199. $content .= "n";
  200. $rows_count += 1;
  201. }else{
  202. $rows_count += 1/$width;
  203. }
  204. $content .= $l;
  205. }
  206. return $rows_count;
  207. }
  208. /**
  209. *
  210. * Replacement function (replace once)
  211. * @param unknown_type $needle
  212. * @param unknown_type $replace
  213. * @param unknown_type $haystack
  214. */
  215. function str_replace_once($needle, $replace, $haystack) {
  216. $pos = strpos($haystack, $needle);
  217. if ($pos === false) {
  218. return $haystack;
  219. }
  220. return substr_replace($haystack , $replace, $pos, strlen($needle));
  221. }
  222. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles