1

I'm adding a lon string of text onto an image using PHP GD library.

The string may be 2 lines long, or 3.

The problem is that it's taking the with of the string with a \n linebreak in it, and then centering that, but its not centering line two.

It creates images like this:

enter image description here

When I want it to be centered for both lines.

Here's the code I have:

header('Content-type: image/jpeg');

$image       = imagecreatefromjpeg($_FILES['image']['tmp_name']);
$imagewidth  = imagesx($image);
$imageheight = imagesy($image);

$black       = imagecolorallocatealpha($image, 0, 0, 0, 40);
imagefilledrectangle($image, 0, 0, $imagewidth, 207, $black);

$white       = imagecolorallocate($image, 255, 255, 255);
$text        = wordwrap($_POST['headline'], 33, "\n" );

$font        = 'HelveticaWorld-Bold.ttf';
$fontsize    = 45;
$fontangle   = 0;

### Get exact dimensions of text string
$box = @imageTTFBbox($fontsize, $fontangle, $font, $text);

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth / 2) - ($textwidth / 2) - 2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2);
$ycord = 80;

function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
  for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
  for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
  $bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
  return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}

### imagettftext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $font, $text);
$stroke_color = imagecolorallocate($image, 0, 0, 0);
imagettfstroketext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $stroke_color, $font, $text, 7);

imagejpeg($image, NULL, 100);
imagedestroy($image);         
st0rk
  • 421
  • 2
  • 5
  • 11

0 Answers0