Center aligning multiple lines of text with GD and PHP

php gd text
gdtext github

I'm trying to print multiple lines of text on an image and center align them.

i.e.

    This isA string of text

Right now, I only have the left position for the whole string. Any shortcuts on getting that to work? I think it might have to be a getttfbox on the whole string, then an explode on the line breaks, then center the new text inside that larger ttfbox. That's a pain in the ass...

EDIT: Came up with a solution:

    foreach ( $strings as $index => $string ) {
        $parts = explode ( "\n", $string['string'] );
        if ( count ( $parts ) > 1 ) {
            $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $string['string'] );
            $width = $bounds[2] - $bounds[0];
            $height = $bounds[3] - $bounds[5];
            $line_height = $height / count ( $parts );

            foreach ( $parts as $index => $part ) {
                $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $part );
                $new_width = $bounds[2] - $bounds[0];
                $diff = ( $width - $new_width ) / 2;
                $new_left = $string['left'] + $diff;

                $new_string = $string;
                $new_string['left'] = $new_left;
                $new_string['top'] = $string['top'] + ($index * $line_height);
                $new_string['string'] = $part;
                $new_strings[] = $new_string;
            }
        }
    }

    if ( $new_strings )
        $strings = $new_strings;

In this case, each $string is an array with some information about how and what to print. Hope that helps someone.

You can use stil/gd-text class. Disclaimer: I am the author.

<?php
use GDText\Box;
use GDText\Color;

$img = imagecreatefromjpeg('image.jpg');

$textbox = new Box($img);
$textbox->setFontSize(12);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(0, 0, 0));
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('center', 'top');
// it accepts multiline text
$textbox->draw("This is\na string of text");

Demonstration:

imagettftext - Manual, Depending on which version of the GD library PHP is using, when fontfile does not This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. or something similar) and needs to format the text into multiple lines. If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

Here is a function that will use the imagettfbbox you mentioned, I can't help with the automatic wordwrapping, but maybe as you suggested, split the string ahead of time.

function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
  $bbox = imagettfbbox($size, $angle, $fontfile, $text);
  $dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;
  $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;
  $px = $x-$dx;
  $py = $y-$dy;
  return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}

Edit: Also found this in the PHP documentation comments...

Here's a simple function to wrap text going into an image. It'll wrap onto as many lines as it needs to, but $angle has to be zero. The $width parameter is the width of the image.

function wrap($fontSize, $angle, $fontFace, $string, $width)
{
  $ret = "";
  $arr = explode(' ', $string);
  foreach ( $arr as $word )
  {
    $teststring = $ret.' '.$word;
    $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
    if ( $testbox[2] > $width ){
      $ret.=($ret==""?"":"\n").$word;
    } else {
      $ret.=($ret==""?"":' ').$word;
    }
  }
  return $ret;
}

How to write Multiline Long text on image in PHP, To write multiline long text using imagettftext is not default functionality. The main function which is needed to align the text: PHP comes with GD library and it provides function imagettftext which is used to display text on an image, but this function has one critical $text = “This is to center alignn the text on image”;. Multiple blocks of text. If you have many blocks of text you would like to center, you can use CSS inside <style></style> tags in the head section of the page or in an external style sheet. See the example code below for how to set all text inside the <p></p> tags to be centered.

You could use the excellent gd-text library. If you use composer, an example could be this:

<?php
require __DIR__.'/../vendor/autoload.php';

use GDText\Box;

$im = imagecreatetruecolor(500, 500);
$backgroundColor = imagecolorallocate($im, 0, 18, 64);
imagefill($im, 0, 0, $backgroundColor);

$box = new Box($im);
$box->setFontFace(__DIR__.'/Pacifico.ttf'); // http://www.dafont.com/pacifico.font
$box->setFontSize(80);
$box->setFontColor([255, 255, 255]);
$box->setTextShadow([0, 0, 0, 50], 0, -2);
$box->setLeading(0.7);
$box->setBox(20, 20, 460, 460);
$box->setTextAlign('center', 'center');
$box->draw("Pacifico");

header("Content-type: image/png");
imagepng($im);

Multiline text centering · Issue #219 · Intervention/image · GitHub, Text methods callback parameter align doesn't center multiline text. I'm using GD library. See the image below. The problem is, it's not center aligned on the image itself, it's center aligned relative to the other lines of text. i.e. the image could be 500px wide, the left of the text could be 100px, the text width could be 150px and have 2 lines, and the text should be center aligned on itself.

This is my code which works:

function textWithImage($text){  
                $imagePath="/images/fb-share-bg.jpg";
                $im = imagecreatefromjpeg($imagePath);
                $txtColor = imageColorAllocate($im, 255, 255, 255);  
                $font="/fonts/OpenSans-Bold.ttf";
                $description=$text;
                $in =  wordwrap($description,50,"|",true);
                $st = explode("|",$in);
                //$inStrArr=str_split($description,60);
                $inStrArr=$st;
                $addOnYVal=0;
                foreach($inStrArr as $key=>$value){
                    if($key!=0){
                        $addOnYVal+=40;
                    }
                    list($x, $y) = pc_ImageTTFCenter($im, $value, $font, 20,$addOnYVal);
                    ImageTTFText($im,20,0, $x, $y, $txtColor, $font, $value);
                }

               $newImagename="/uploads/".$img;
               imagejpeg($im, $newImagename,100);

} // Enf of textWithImage function



function pc_ImageTTFCenter($image, $text, $font, $size, $addOnYVal) {
    // find the size of the image
    $xi = ImageSX($image);
    $yi = ImageSY($image);

    // find the size of the text
    $box = ImageTTFBBox($size, $angle, $font, $text);

    $xr = abs(max($box[2], $box[4]));
    $yr = abs(max($box[5], $box[7]));

    // compute centering
    $x = intval(($xi - $xr) / 2);
    $y = intval(($yi + $yr) / 2) +  + $addOnYVal;;

    return array($x, $y);
}

// Calling function
$text = "This is to center alignn the text on image";

textWithImage($text);

//  Output: Image will be saved in the upload folder

Vertically Aligning Text In Image (Gd) - PHP Coding Help, I want this dynamic text to vertically align in the middle, and I have had a but because the text needs to span multiple lines of text, I needed to  Parameters. size. The font size in points. angle. Angle in degrees in which text will be measured.. fontfile. The path to the TrueType font you wish to use. Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

Get the length of the string (strlen), and an average width of each letter, multiply the strlen result by the average width and then subtract that from your horizontal position.

$text="center this";
$h=50;
$h=(strlen($text)*15)-$h;

Tell me if it works because I have never tried this

php gd vertical text an image, Center aligning multiple lines of text with GD and PHP. I'm trying to print multiple lines of text on an image and center align them. i.e. This isA string of text Right  Align One Line of Text. This is actually the easiest of the bunch. If you only want to align one line of text, like a title, with a picture, then use one of three commands; "top," "middle," or "bottom." Like so: <ALIGN="top"> <ALIGN="middle"> <ALIGN="bottom">

CSS Layout - Horizontal & Vertical Align, Center Align Text. To just center the text inside an element, use text-align: center;. This text is centered. The special is, you can define the alpha-value of the line (0 = normal smooth line, 127 = fully transparent). Change whatever you want to make it better, but post your results ;) <?php

Drawing Centered Text (PHP Cookbook), Problem. You want to draw text in the center of an image. the text. For built-in GD fonts, use the pc_ImageStringCenter( ) function shown in Example 15-1. CSS Rounded Corners CSS Border Images CSS Backgrounds CSS Colors CSS Gradients CSS Shadows CSS Text Effects CSS Web Fonts CSS 2D Transforms CSS 3D Transforms CSS Transitions CSS Animations CSS Tooltips CSS Style Images CSS object-fit CSS Buttons CSS Pagination CSS Multiple Columns CSS User Interface CSS Variables CSS Box Sizing CSS Flexbox CSS

how to type long text in Intervention image, in font size 12 estimate 6-7 words come in one line and remaining words are disappearing due to they all are formatted in single line is there  Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. w3schools .com THE WORLD'S LARGEST WEB DEVELOPER SITE

Comments
  • Please don't edit your answer into your question but instead write a new answer (and accept it, if thats the solution that worked for you).
  • I downloaded your code. It works perfectly fine, but probably one of the reasons why not many people is using it, is because it has and downloads a lot of dependencies! your system to align the box is heavier than the client and the server of my plataform together. if you could somehow make it work without the content of /vendor/, more like stand alone method or a function, then you would have something great.
  • The problem is, it's not center aligned on the image itself, it's center aligned relative to the other lines of text. i.e. the image could be 500px wide, the left of the text could be 100px, the text width could be 150px and have 2 lines, and the text should be center aligned on itself.
  • Then I'm going to guess you'll need line by line imagettftext_cr() as you already mentioned. php.net/manual/en/function.imagettftext.php search forthe post by "sk89q" on 14-Mar-2008 03:36
  • Yeah, it's not exactly what I need still. It's cool, I can write the function, I just was hoping someone would have a shortcut
  • Yeah I'm not aware of a PHP function that can do this out of the box without iteration.
  • That's not gonna really cut it for what I'm trying to do. Thanks though.