set width of image based on text it displays
Posted on 2007-07-28
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)
$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);