Jump to content

[SOLVED] GD + Dynamic string length => width


nbarone

Recommended Posts

I am trying to create a title on the top of each dynamic page. The pages will be created and deleted regularly via a CMS, so it must stay dynamic.

 

I am having an issue figuring out how to  calculate image width based upon string length and font width. Basically, I can narrow it down to "close", but then when I use a string that's all CAPS, the string falls off of the image. I would also like the string to be centered in the image (best if the image was only ~5 pixels larger than the string on each side.

 

 

Any input is appreciated.

 

<?php
$font = "coopheavy.ttf"; 

$title = $_REQUEST['title'];
$imw = strlen($title) * 13;

header ("Content-type: image/png"); 
$image = imagecreate($imw, 30);

$bg = imagecolorallocate($image, 255, 255, 255);
$fontColor = imagecolorallocate($image, 0, 0, 0);

imagettftext($image, 24, 0,0, 24, $fontColor, $font, $title);

imagepng($image);
imagedestroy($image);

?>

Link to comment
https://forums.phpfreaks.com/topic/164251-solved-gd-dynamic-string-length-width/
Share on other sites

I would think that you'd have to extract size information from the font data/file itself to know how wide each character would be.  Something else you could try to do is generate the text on a much larger contrasting canvas (like a green screen) and then detect where the text you've entered starts and ends and make the image the appropriate size.

you can use http://us3.php.net/manual/en/function.imagettfbbox.php to calculate the height/width of the text that will be printed

 

This is exactly what I was looking for, thank you.

 

Here is my new code, works great:

<?php
$font = "coopheavy.ttf"; 
$title = $_REQUEST['title'];

$img_arr = imagettfbbox(24,0,$font,$title);
$bot_right = $img_arr[2];

header ("Content-type: image/png"); 

$image = imagecreate($bot_right+20, 30);
$bg = imagecolorallocate($image, 255, 255, 255);
$fontColor = imagecolorallocate($image, 0, 0, 0);

imagettftext($image, 24, 0, 10, 24, $fontColor, $font, $title);
imagepng($image);
imagedestroy($image);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.