Page 1 of 1

Imagettftext() kerning problem

Posted: Sat Jan 02, 2010 4:53 pm
by kerryb
Hi,

I'm trying to create some text in an image using Imagettftext() functions. I found some code from 999 tutorials here, and got it to work work some modifications :

Code: Select all

$theText        = "999 Tutorials, transparent text";
$fontSize    = 18;
$angle        = 0;
$font            = "./fonts/Ariendesse.ttf";
header("Content-type: image/png");
$size = imageTTFBBox($fontSize, $angle, $font, $theText);
$height = abs($size[5] - $size[3]);
$width = abs($size[2] - $size[0]);
$image = imageCreateTrueColor($width,$height);
imageSaveAlpha($image, true);
ImageAlphaBlending($image, false);
$transparentColor = imagecolorallocatealpha($image, 200, 200, 200, 127);
Imagefill($image, 0, 0, $transparentColor);
//$background_color = imagecolorallocatealpha($image, 0,0,0,12);
$textColor = imagecolorallocate($image, 200, 0, 0);
$result = imagettftext($image, $fontSize, 0, 0, $height, $textColor, $font, $theText); //** Problem here
imagepng($image);
imagepng($image, "textImage.png");
imagedestroy($image);
The problem is that in the resulting image (see below), the under-hanging parts of 'p' and commas are cropped. This is because Imagettftext() takes it origin from the lower left character but not the lowest character that is used. Now I could compensate for it by adding a few extra pixels the the y coordinate but does anyone know how I can automatically compensate for a change in font size ?
textImage.png
textImage.png (4.32 KiB) Viewed 521 times

Re: Imagettftext() kerning problem

Posted: Sat Jan 02, 2010 6:24 pm
by manohoo
I am afraid that PHP does not have an automatic answer to your problem. I played around with different font sizes in order to find an optimal factor, the best I could do is to multiply $height by 0.8:

Code: Select all

$height = 0.8*abs($size[5] - $size[3]);
Not the perfect solution, but it does a reasonable job.

Re: Imagettftext() kerning problem

Posted: Sat Jan 02, 2010 6:35 pm
by kerryb
manohoo wrote:I am afraid that PHP does not have an automatic answer to your problem. I played around with different font sizes in order to find an optimal factor, the best I could do is to multiply $height by 0.8:

Code: Select all

$height = 0.8*abs($size[5] - $size[3]);
Not the perfect solution, but it does a reasonable job.
thanks manohoo, I suspected there wasn't an in-built solution