在imagettftext()中换行文本

i got this script to generate an image out of a random jpg in a directory, adding a random slogan from a database:

<?php

header('Content-type: text/html; charset=utf-8'); 

include '../connect.php';
require_once 'random.php';

$timestamp = time();
$date = date("d.m.Y_G", $timestamp);


$slogan = $mysqli->query("SELECT `text` FROM `slogans` ORDER BY RAND() LIMIT 1");

    $slogan_txt = $slogan->fetch_assoc();



    $bg = get_rand_img('../../images/');
    $imgPath = '../../images/' .$bg;

$text = $slogan_txt[text];
$image = $imgPath; 
$font = "font.TTF";
$font_size = "25";

$image_2 = imagecreatefromjpeg($image);
$black = imagecolorallocate($image_2,0,0,0);

$image_width = imagesx($image_2);  
$image_height = imagesy($image_2);

$text_box = imagettfbbox($font_size,$angle,$font,$text);
$text_width = $text_box[2]-$text_box[0]; // lower right corner - lower left corner
$text_height = $text_box[3]-$text_box[1];

$x = ($image_width/2) - ($text_width/2);
$y = ($image_height/2) - ($text_height/2);

imagettftext($image_2,$font_size,0,$x,$y,$black,$font,$text );

header ("Content-type: image/png");
imagejpeg($image_2);



?>

works fine so far.

Now there are some slogans with to much words for one row. i need them to be wrapped and also be centered!

can't use wordwrap in imagettftext(), so i need to explode it somehow.

i found some functions on the web, but they dont work as expected. maybe i just dont know how to combine them with my existing code!

maybe someone got a workign example from own projects?

thanks so far!

2个回答



嗯,它现在有用了。</ p>

在这里找到了一些有趣的东西,就是这样! 只需要添加计算从哪里开始文本(响应imagesize)。</ p>

GDtext by stil </ p>

谢谢!</ p>
</ div>

展开原文

原文

Well, it worked now.

Found something interesting here and thats it! Just needed to add the calculation for where to start with the text (responding to imagesize).

GDtext by stil

Thanks!

This explodes a string and puts it text into a second string if the first is longer then 14, i guess you could build up on this.

$string = "";
$string2 = "";
$name = explode(" ", $name);
foreach ($name as $n) {
    if (strlen($string) + strlen($n) > 14) {
            $string2 .= $n . " ";
        } else {
            $string .= $n . " ";
        }    
}

for centering the text you would need to do something like: (imagesisex/2) - digits * pixelsize

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐