Stefan Dunn
Stefan Dunn

Reputation: 5513

imagettftext - Center align text same way CSS does it

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

Upvotes: 1

Views: 879

Answers (0)

Related Questions