Today, when I accidentally browsed the web page, I found a long microblog that could convert text into png images, so I just studied the PHP text conversion method. In fact, as long as I used the PHP extension library, the GD library is used to generate images, and then the image function is used to generate images. After the code is written, it is found that if there are too many texts, the image will exceed the screen width, resulting in the right pull of the browser, think about whether there is any way to enable the image to wrap automatically. GG found an article, and then spliced it to realize automatic line feed of the text image by judging the string and intercepting the string. The following code is pasted, to learn:
Copy codeThe Code is as follows: <? Php
Header ("Content-type: image/png ");
Mb_internal_encoding ("UTF-8"); // sets the Encoding
Function autowrap ($ fontsize, $ angle, $ fontface, $ string, $ width ){
// These variables are the font size, angle, font name, string, and preset width.
$ Content = "";
// Split the string into one word and save it to the array letter.
For ($ I = 0; $ I <mb_strlen ($ string); $ I ++ ){
$ Letter [] = mb_substr ($ string, $ I, 1 );
}
Foreach ($ letter as $ l ){
$ Teststr = $ content. "". $ l;
$ Testbox = imagettfbbox ($ fontsize, $ angle, $ fontface, $ teststr );
// Determine whether the spliced string exceeds the preset width
If ($ testbox [2]> $ width) & ($ content! = "")){
$ Content. = "\ n ";
}
$ Content. = $ l;
}
Return $ content;
}
$ Bg = imagecreatetruecolor (300,290); // create a canvas
$ White = imagecolorallocate ($ bg, 255,255,255); // create a white image
$ Text = "some time ago, when I used PHP's GD library, I had a long time to struggle with automatic text wrapping. Although newline can be implemented by inserting \ n, the effect of force-limiting each number of characters to wrap lines is poor considering that there are both Chinese and English characters in the text. Later, I finally found a new line feed method in English. The general principle is to use spaces as separators, separate strings into words, and splice them one by one, determine whether the length of the canvas is exceeded. If it exceeds the canvas size, wrap the text and splice the canvas. Otherwise, splice the canvas. Considering that Chinese characters need to be separated, I made some modifications. The complete code is as follows. ";
$ Text = autowrap (12, 0, "simsun. ttc", $ text, 280); // wrap automatically
// If the file is encoded as GB2312, remove the downstream comments.
// $ Text = iconv ("GB2312", "UTF-8", $ text );
Imagettftext ($ bg, 12, 0, 10, 30, $ white, "simsun. ttc", $ text );
Imagepng ($ bg );
Imagedestroy ($ bg );
?>