troubleshooting Question

set width of image based on text it displays

Avatar of ellandrd
ellandrdFlag for Ireland asked on
Web Languages and StandardsFonts TypographyPHP
4 Comments1 Solution347 ViewsLast Modified:
I can create a image with text on it, but my problem is getting the width of the image correct each time.

I want the width to fit the text nicely - not too much gaps to the left or to the right.

The text can change depending on what users type so I cant set a fixed width for the image.  I'm using a custom font (verdana.ttf) and to display 1 character I have worked out it takes a width of 7.8.    I cant tell if this is pixels or what?  

However I have tried working out some calculations to dynamically work out the width based on the number of chars, numbers, dots, dashes, special chars etc etc but it never works out correctly.

My PHP application takes a string of text and searches for a email address.  if it find a email address, it returns an image with the email address displayed on it so it cant be indexed as text by search engines.  

According to the web standards an email address can have X amount of characters and numbers (A-Z 0-9), 1 at symbol (@), X amount of dots (.), X amount of dashes (-) and X amount of underscores (_) to be valid for most email programs.

This is my snippet so far (that does not work out width correctly)

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

$email = fcnDecode(trim($_GET['input']));

$font = 'verdana.ttf';
$chars = 7.8;
$ats = 9;
$dots = 3;
$dashes = 7;
$underscores = 8;

$total_dots = substr_count($email,'.');
$total_ats = substr_count($email,'@');
$total_dash = substr_count($email,'-');
$total_underscore = substr_count($email,'_');
$total_chars = fcnCountChars($email);

$char = ($total_chars * $chars);
$at = ($total_ats * $ats);
$dot = ($total_dots * $dots);
$dash = ($total_dashes * $dashes);
$underscore = ($total_underscores * $underscores);

$length = $char + $at + $dot + $dash = $underscore;

$im = imagecreate($length,14);  <--- 14 here is the height of the image BTW
$bg = imagecolorallocate($im,244,244,244);
$fg = imagecolorallocate($im,33,33,33);

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros