/    Sign up×
Community /Pin to ProfileBookmark

GD + Dynamic string length => width

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.

[code=php]<?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);

?>[/code]

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@aj_nscJun 30.2009 — I had this problem before, and I got it close with probably 95&#37; of strings, I could never get them all. You just have to perform some calculations and also, the following code might help you out:

[code=php]
$width = imagegetfontwidth($yourfont)*strlen($yourstring);
[/code]
×

Success!

Help @nbarone spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...