GD text justify

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
The following code works partially.
If Justify is set to 0, I see 3 separate lines of text left justified

but when I try to right or center justify I only get the first line.
It is
justified but out of vertical position as well it seems. Can someone
this or point me to a working function. TIA
//  $Justify:   0=left 1=right 2=center - watch word wrap
function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=0,
$Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12,
$color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
   $angle = 0;
   $_bx = imageTTFBbox($fsize,0,$font,$text);
   $s = split("[\n]+", $text);  // Array of lines
   $nL = count($s);  // Number of lines
   $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
   $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H;
   $im = imagecreate($W, $H) or die("Cannot Initialize new GD image
   $background_color = imagecolorallocate($im, $bgcolor[0],
$bgcolor[1], $bgcolor[2]);
   $text_color = imagecolorallocate($im, $color[0], $color[1],
   if ($Justify == 0){ //Justify Left
      imagettftext($im, $fsize, $angle, $X, $fsize, $text_color,
$font, $text);
   else {
      $_b = imageTTFBbox($fsize,0,$font,$text);
      $_H = abs($_b[5]-$_b[3]);
      for ($i=0; $i<$nL; $i++) {
         $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
         $_W = abs($_b[2]-$_b[0]);
         if ($Justify == 1) $_X = $W-$_W;  // Justify Right
         else $_X = abs($W/2)-abs($_W/2);  // Justify Center
         $__H += $_H;
         imagettftext($im, $fsize, $angle, $_X, $__H, $text_color,
$font, $s[$i]);
         $__H += $Leading;
   header("Content-type: image/png");
imagettfJustifytext("Hello there\nMy name is Ricky\nByee");

Re: GD text justify


The vertical position exceeds the height, so you should be able to

    $__H += $_H;


    $__H += abs($_b[5] - $_b[3]);

There's also an alignment function at:


John Peters

Quoted text here. Click to load it

Re: GD text justify

Quoted text here. Click to load it

Yes this works thank you. It seems to have been a scope problem
with the for loop since prior to the loop $_H is assigned these
same values. I took out the prior assignment and replaced as
you showed in the for loop and all is well. BTW I also gave the
other a try but couldn't get it to work straight away. I saw it
in my original searches but passed over it because of the date
and the way it passed the image ref. Thanks again.
Quoted text here. Click to load it

Site Timeline