Jump to content

Generate image with text issue - centering text


matthewod

Recommended Posts

I am working on setting up an on the fly business card generator and I am having some issues!  

 

For some reason I cannot center my text.  Here is my code:

 

 



$image_width = 600;
$x_name = (($image_width - strlen($name))/2);
$x_address = (($image_width - (strlen($address_line)))/2);
$x_contact = (($image_width - strlen($contact_line))/2);

imagettftext($jpg_image, 20, 0, 300, 220, $black, $font_path, $name);
imagettftext($jpg_image, 16, 0, $x_address, 300, $white, $font_path, $address_line);
imagettftext($jpg_image, 16, 0, $x_contact, 325, $white, $font_path, $contact_line);

imagejpeg($jpg_image);


 

 

Where X is the left margin.  All my variables are working fine.  But this what I am getting:


 

I am not sure what I am doing wrong but any help would be appreciated!  

 

Thank you!

 

Link to comment
Share on other sites

Are you using this to center the text?

 

 

$x_name = (($image_width - strlen($name))/2);
$x_address = (($image_width - (strlen($address_line)))/2);
$x_contact = (($image_width - strlen($contact_line))/2);

You cannot minus the character length of your string from the total width of your image.

 

Instead you need to use imagettfbbox. This will return the x and y boundaries of your text in pixels. You would take away the 'lower right corner, X position' of your text from the total width of your image and then divide what is left by 2 to calculate the correct x position of your text so it is centered within your image.

 

Example code

// The text to draw
$text = 'Hello World';

// get the bounding box of our text
$bbox = imagettfbbox(20, 0, $font, $text);

// calculate the center X position of our text
    // 1. get the image width
    // 2. minus the texts lower right corner, X position
    // 3. divided whats is left by 2
$x = (imagesx($im) - $bbox[2]) / 2;
// Y position of our text
$y = 50;

// Add the text
imagettftext($im, 20, 0, $x, $y, $black, $font, $text);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.