php text to image wrapping method

  • 2020-05-30 19:44:05
  • OfStack

Today accidentally browsing the net surface to find a long weibo, it can be text into png pictures, so they study 1 down PHP text to image the way, in fact, as long as it is used to PHP extension libraries, GD library to generate images, again through the image function, code written later, found that if too many words, pictures will be more than the width of the screen, causing the appearance of the browser right brace, so think is there any way can make the picture to word wrap, through GG, found 1 article, Text image wrapping is realized by judging the string and stitching it together again. The following code is posted to learn:


<?php
header ("Content-type: image/png");
mb_internal_encoding("UTF-8"); //  Set the coding 
function autowrap($fontsize, $angle, $fontface, $string, $width) {
//  These are the variables   The font size ,  The Angle ,  The name of the font ,  string ,  The default width 
 $content = "";
 //  Split the string 1 All words   Save to an array  letter  In the 
 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);
  //  Determines whether the concatenated 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 white 
$text = " Practice using it some time ago  PHP  the  GD  Library, for text wrap for a long time. Although it can be inserted   \ n  Implement line breaks, but given that the text is in both Chinese and English, forcing a line break for every number of words is not very effective. Finally I found it 1 A line wrap method that takes a space as a separator and splits the string into 1 Word by word, and then again 1 after 1 The land is spliced in 1 Then, judge whether the length is longer than the canvas. If the length is longer than the canvas, line feed and then splice; otherwise, continue to splice. Considering that Chinese needs to separate each character, I went ahead 1 Click modify, the full code is as follows. ";
$text = autowrap(12, 0, "simsun.ttc", $text, 280); //  Line wrapping 
//  If the file code is  GB2312  Please remove the downstream comments 
// $text = iconv("GB2312", "UTF-8", $text);
imagettftext($bg, 12, 0, 10, 30, $white, "simsun.ttc", $text);
imagepng($bg);
imagedestroy($bg);
?>


Related articles: