我使用PHP和GD库制作了一个代码,该代码接收字符串作为输入,并将其分成几行,以便可以放入图像中。问题是,取决于我键入的文本,它会在随机点处停止。例如,使用以下文本作为输入:
Lorem ipsum dolor坐下,奉献己任,sius do eiusmod tempor incididunt ut Labore et dolore magna aliqua。尽量不要抽烟,不要因抽烟而锻炼。 Duis aute irure dolor in reprehenderit in volttable velit esse cillum dolore eu fugiat nulla pariatur。不会出现意外的圣人,反而会在犯规的情况下动手动手。
我的代码是这样的:
<?php
function createStory($content){
$text = $content;
$jpg_image = imagecreatefromjpeg('imagebuilder/footage/story1.jpg');
$white = imagecolorallocate($jpg_image, 255, 255, 255);
$font_path = 'Arial.ttf';
$words = explode(" ",$text);
$proccessedtext = "";
$line = "";
$line .= $words[0] . " ";
for($i = 1; $i < count($words); $i++){
$bbox = imagettfbbox(25, 0, $font_path, $line);
$width = $bbox[4]-$bbox[0];
if($width<700){
$line .= $words[$i] . " ";
}else{
$proccessedtext .= $line . " \n".$words[$i]. " ";
$line = "";
}
}
imagettftext($jpg_image, 25, 0, 75, 600, $white, $font_path, $proccessedtext);
imagejpeg($jpg_image, "imagebuilder/created/readyStory.jpg");
imagedestroy($jpg_image);
return("/imagebuilder/created/readyStory.jpg");
}
?>
我的代码中是否有任何错误,或者是库中的错误?
答案 0 :(得分:1)
非常简单:请注意,$processedText
在超过最大宽度之前不会收到$line
的内容!因此,在任何给定时间,它只会收到整行以及溢出的一个单词。因此,如果您剩余的文字没有超出当前行一个额外的单词,那么剩下的文字仍需要处理。尝试在for循环之后直接添加$processedText .= $line;
:
<?php
function createStory($content){
$text = $content;
$jpg_image = imagecreatefromjpeg('imagebuilder/footage/story1.jpg');
$white = imagecolorallocate($jpg_image, 255, 255, 255);
$font_path = 'Arial.ttf';
$words = explode(" ",$text);
$proccessedtext = "";
$line = "";
$line .= $words[0] . " ";
for($i = 1; $i < count($words); $i++){
$bbox = imagettfbbox(25, 0, $font_path, $line);
$width = $bbox[4]-$bbox[0];
if($width<700){
$line .= $words[$i] . " ";
}else{
$proccessedtext .= $line . " \n".$words[$i]. " ";
$line = "";
}
}
$processedText .= $line;
imagettftext($jpg_image, 25, 0, 75, 600, $white, $font_path, $proccessedtext);
imagejpeg($jpg_image, "imagebuilder/created/readyStory.jpg");
imagedestroy($jpg_image);
return("/imagebuilder/created/readyStory.jpg");
}
?>