1

I've seen so many demos on how to have the text aligned in the center of an image, but I am looking to have the text center aligned so that it appears the same as CSS text-align:centeror photoshop's center align.

How can I achieve this with imagettftext?

This is my code so far:

    $new_image = imagecreatefromjpeg(get_template_directory()."/images/homepage/blackboard.jpg"); // Load up the blackboard image.
    $white = imagecolorallocate($new_image, 255, 255, 255); // Create a white colour
    $font_path = get_template_directory()."/fonts/PermanentMarker.ttf"; // Set font
    $text = get_field("blackboard_message", $page->ID); // Create text object
    $text_length = 19;
    $text = wordwrap($text, $text_length, "\n", true);
    imagettftext($new_image, 16, 0, 60, 185, $white, $font_path, $text); // Add text to image.
    $mask = imagecreatefrompng(get_template_directory()."/images/homepage/blackboard-mask.png"); // Load the mask
    imagesavealpha($mask, false); // Do not save full alpha channels
    imagealphablending($mask, false); // Disable alpha blending
    imagecopy($new_image, $mask, 55, 160, 0, 0, 224, 285); // Copy mask on top of blackboard image.
    imagejpeg($new_image, get_template_directory()."/images/homepage/blackboard/blackboard-message-$modified_unix_timestamp.jpg");

The end result should look like this:

Center aligned text

Stefan Dunn
  • 5,363
  • 7
  • 48
  • 84
  • You use http://php.net/manual/en/function.imagettfbbox.php to get the bounding box of the text, and then take the top left X and top right X values to get the width of the text, and then use this to position it in the center of your canvas – Jamie Bicknell Oct 01 '14 at 11:19
  • See the code in this answer on how to do it: http://stackoverflow.com/a/14517450/128161 – Jamie Bicknell Oct 01 '14 at 11:20
  • @JamieBicknell This is precisely what I do not want to do, that just centers the text on the canvas, not centre align the text. – Stefan Dunn Oct 01 '14 at 12:14

0 Answers0