center a text and write it on image in php
<p>this is a function i came up with to write on image </p>

<p>the only problem remained is how to center the text horizontally </p>

<pre><code> $angle = 0;
 $_bx = imageTTFBbox($fsize,0,$font,$text);
 $s = split("[\n]+", $text);  // Array of lines
 $nL = count($s);  // Number of lines
  // If Width not initialized by programmer then it will detect and assign perfect width.
 $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;   
  // If Height not initialized by programmer then it will detect and assign perfect height.
 $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL&gt;1?($nL*$Leading):0):$H;   

 //$back_pattern is a gif image address
 $im = @imagecreatefromgif($back_pattern); 


  // Create alpha-nummeric string
  $alpha = range("a", "z");
  $alpha = $alpha.strtoupper($alpha).range(0, 9);
  // Use the string to determine the height of a line
  $_b = imageTTFBbox($fsize,0,$font,$alpha);
  $_H = abs($_b[5]-$_b[3]);
  $__H=abs($H/2)-abs($_H/2);
  for ($i=0; $i&lt;$nL; $i++) {
   $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
   $_W = abs($_b[2]-$_b[0]);
   //Defining the X coordinate.
   if ($Justify == 1) $_X = $W-$_W;  // Justify Right
   else $_X = abs($W/2)-abs($_W/2);  // Justify Center
   //Defining the Y coordinate.
   $__H += $_H;
   //running and writing on image 
   imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
   $__H += $Leading;
  }
</code></pre>
