I'm going to assume that you're using GD, and it looks as though you're going about this the most difficult way imaginable. Also, it looks as though you may've skipped, or at least skimped on, the documentation
Use the imagettftext()
function to create text using a TrueType font.
Use the imagettfbbox()
function to find out the dimensions of a particular string as rendered in your font of choice. Once you get the dimensions, then it's easy to figure ought how far left and above center you need to render it to center-align it.
This will save you a lot of math, and save you from using PHP's fugly bulit-in fonts.