Please Help W/ Centering Text Using Php & GD
I am hoping that someone better with GD Library than myself (and that is probably most of you) can help me figure out how to line the text up in the center of the image. I can figure out how to center the text vertically but can not center the text horizontally because the size of the word changes based on how many characters are used (The user types in their name and the script displays it over the image). I have read quite a few tutorials online on doing this but I was still unable to get it right due to my limited GD experiance. The code is below.
Thank you.
<?php
header("Content-type: image/png");
$user = $_GET['user'];
$image = imagecreatefrompng("temp.png");
$user_width = imagettfbbox(9, 0, "tahoma.ttf", $user);
$x_value = (200 - ($user_width[2] + 113));
$color = imagecolorallocate($im, 165, 164, 164);
imagettftext($image, 9, 0, $x_value, 16, $color, "tahoma.ttf", $user);
imagepng($image);
imagedestroy($image);
?>
EGS posted this at 03:47 — 18th June 2005.
They have: 161 posts
Joined: Jan 2005
<center><?php
header("Content-type: image/png");
$user = $_GET['user'];
$image = imagecreatefrompng("temp.png");
$user_width = imagettfbbox(9, 0, "tahoma.ttf", $user);
$x_value = (200 - ($user_width[2] + 113));
$color = imagecolorallocate($im, 165, 164, 164);
imagettftext($image, 9, 0, $x_value, 16, $color, "tahoma.ttf", $user);
imagepng($image);
imagedestroy($image);
?></center>
Does that work ?
Busy posted this at 10:47 — 18th June 2005.
He has: 6,151 posts
Joined: May 2001
VG_KING, it's not an HTML issue, it's GD issue, good try thou
frentjay, I found the following at php.net (http://nz.php.net/manual/en/function.imagettftext.php)
function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L') {
//check width of the text
$bbox = imagettfbbox ($size, $angle, $font, $text);
$textWidth = $bbox[2] - $bbox[0];
switch ($alignment) {
case "R":
$x -= $textWidth;
break;
case "C":
$x -= $textWidth / 2;
break;
}
//write text
imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);
}
I don't use GD (only image::magick) so am unable to test it for you, hope it helps
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.