By judging the string and intercepting the string and then splicing it together, the text image will automatically wrap the line. the following code is used to paste the text into a png image when you accidentally browse the web page, as a matter of fact, as long as the PHP Extension library is used, the GD library is used to generate images, and then the image function is used to generate images. after the code is written, I found that if there are too many texts, the image will exceed the screen width, leading to the appearance of the right pull bar of the browser. so I wonder if there is any way to enable the image to wrap automatically, through GG, an article was found, and the text image is automatically wrapped by judging the string and intercepting the string. the following code is pasted to learn:
The code is as follows:
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 $ 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 );
?>