I have the following code, I'm just wondering if there is an easy way to center the text. Thanks.

<?php
$im = @imagecreate (550,15);
$background_color = imagecolorallocate ($im, 0, 0, 0);
$text_color = imagecolorallocate ($im, 255, 255, 255);
$time = date("g:i:s A");
$date = date("F j, Y");
$number = "It is " . $time . " on " . $date . "!";
imagestring ($im, 3, 1, 1, $number, $text_color);
header ("Content-type: image/png");
imagepng ($im,'',80);
?>

    I always did it using something along the lines of

    $textwidth = floor(imagefontwidth($font) * strlen($text));
    $textleft = ($picwidth - $textwidth) / 2;
    

      I tend to use imagettfbbox to work out the width of the text, then subtract the width of the text from the width of the image (imagesx), then divide the result by 2 to get the starting position.

      Code looks a little something like:

      //variables:
      //$im = output image ($im=imagecreate...)
      //$col = text color ($col=imagecolorallocate...)
      //$starty = vertical starting position
      //$angle = angle for text to be at
      //$fontsize = font size of output string
      //$fontfile = font file (e.g. $fontfile="/path/to/arial.ttf")
      
      $string="Here is a text string";
      $bbox=imagettfbbox($fontsize,$angle,$fontfile,$string);
      $imwidth=imagesx($im);
      $border=$imwidth-($bbox[2]-$bbox[0]);
      $startx=$border/2;
      //print the string
      imagettftext($im,$fontsize,$angle,$fontfile,$startx,$starty,$col,$string);
      

      HTH,

      ucbones

        Write a Reply...