Imagettftext() kerning problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kerryb
Forum Newbie
Posts: 5
Joined: Mon Sep 29, 2008 12:33 pm

Imagettftext() kerning problem

Post 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 520 times
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: Imagettftext() kerning problem

Post 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.
kerryb
Forum Newbie
Posts: 5
Joined: Mon Sep 29, 2008 12:33 pm

Re: Imagettftext() kerning problem

Post 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
Post Reply