Center variable text length on an image

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
Beauford
Forum Newbie
Posts: 3
Joined: Thu Apr 03, 2008 9:19 pm

Center variable text length on an image

Post by Beauford »

I am completely new to GD and having a minor problem. I have been able to get text on an image and it looks great - problem is that the text will always be a different length and as such the text will not be centered everytime.

How do I set it up so the starting pixel is variable depending on the length of the string. The image is always going to be 800x600.

This is what I am using, but obviously this is not variable.

imagettftext($TheImage, 30, 0, 400, 260, $ColorText, "Arial.ttf", $name);

Also, as a side note. I have an arial.ttf file in the same folder as the script, but it doesn't seem to see it, is there a type of font specific to GD that needs to be used or can it be any font file.

Thanks
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Center variable text length on an image

Post by John Cartwright »

User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Re: Center variable text length on an image

Post by JayBird »

User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Center variable text length on an image

Post by onion2k »

JCart was nearly right. imagefontwidth() and imagefontheight() only work on GD's built in fonts though. You need to use imagettfbbox(). It'll return an array of coordinates ... if you calculate the difference between indexes 0 and 2 (assuming the text isn't angled) you can get the width of the rasterised string, from which you can work out where to put it in order to centre it.
Beauford
Forum Newbie
Posts: 3
Joined: Thu Apr 03, 2008 9:19 pm

Re: Center variable text length on an image

Post by Beauford »

JayBird wrote:Moved this to PHP - Code

Please post in the correct forum in future
My apologies, but is this not general discussion? I see a wide variety of topics here and assumed mine would be appropriate here.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Center variable text length on an image

Post by John Cartwright »

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.
Notice the bolded text in our the description of General Discussion ;)
Post Reply