Back to Top

How to write Multiline Long text on image in PHP

How to write Multiline Long text on image in PHP?

I recently had the case of a project where I was trying to display text on image and I have multiple long texts which I was fetching for third party API.You can not write text horizontally in one line especially on image as it is does not always fit into a given width of the Image so at that time you need to wrap the text to new line as per width of image.

I have googled the solution for this but not found any solution. Then I have posted my query on StackOverflow account but no one replied on my question so I understand that this is a very rare case or no one faced such situation before.

Finally after lots of research i got some basic solution from PHP Manual – imagettfbbox site.but before that i will explain you the use of imagettftext and imagettfbbox function in PHP.

Function Basic Understanding:

The main function which is needed to align the text:


This function Calculate the area occupied by the string of TrueType.This function is not used to display an image but simply determines whether the size and position would have taken a line of text.This returns an array of the coordinates of the rectangle which have the information about the size of the string.


array imagettfbbox (float size, float angle, fontfile string, string text)


This function output text of TrueType to the image


array imagettftext (resource image, size float, float angle, int x, int y, int color, fontfile string, string text)

This function puts the string text in the image. As usual, Parameter color must be a valid color identifier. Angle Parameter defines the angle in degrees of the output string which measured from the horizontal counter-clockwise. Coordinates (x, y) indicate the position of the text. Parameter size determines the font size to be used for text. Font file must be the name or path of the TTF-file in which the font.

The function returns a list of 8 elements. The first pair contain sets of coordinates (x, y) of the upper left corner of the rectangle restricting the text lines in the image and the second pair contain sets of coordinates (x, y) of the upper right corner.and others are the lower(x, y) coordinates.

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 drawback, You can not set the coordinates or width for multiline text.Therefore, You need to expand the function by own self to get desired output otherwise your long text overwrite and looks messy.

Once you understand the basic about imagettftext function in PHP, nothing prevents you from going further explore the possibilities of this function and you can use as you want to.

Let the code

Here is the working example to wrap the text with a given width on image:

In this function, First we explode the string by whitespace and then loop the exploded text and in loop,used condition which will prepare string for single line till the max width of image.and if coordinates are greater than width it will display the text and go for the next line.Here, we are using the imagettfbbox () function to calculate the width of the written text and draw a line below the text using the imageline ().

function image_multiline_text($image, $size, $angle, $xpos, $ypos, $color, $font, $text, $max_width, $next_line = '')
	$split = explode(" ", $text);
	$string = "";
	$new_string = "";
    $box = imagettfbbox($size, 0, $font, $text);
    $text_height = $box[3]-$box[5];
    $count = 0;
	for ($i = 0; $i < count($split); $i++)
		$new_string.= $split[$i] . " ";
		// check size of string
		$tbbox = imagettfbbox($size, 0, $font, $new_string);
        if ($tbbox[4] < $max_width)
			$string = $new_string;
			$new_string = "";
           	$bbox = imagettfbbox($size, 0, $font, $new_string);
            $height =  $bbox[3]-$bbox[5];
            if($text_height > $height && $count > 0){
                $ypos += ($height);
			$tb = imagettftext($image, $size, $angle, $xpos, $ypos, $color, $font, $text);
            $height =  $tb[3]-$tb[5];
            if($height < $text_height){
                $ypos += $height;
			$string = "";
			if ($next_line != '')
				$max_width+= ($xpos - $nextline);
				$xpos = $next_line;

			$ypos = $tb[3] + $height; // change this to adjust line-height.
	imagettftext($image, $size, $angle, $xpos, $ypos, $color, $font, $string); // "draws" the rest of the string
$img = imagecreatefromjpeg('template.jpg');
$black = imagecolorallocate($img, 0x00, 0x00, 0x00);
$font_path = "Arial.ttf";
$text = '';
image_multiline_text($img, 13, 0, 40, 100, $black, $font_path, $text, 400); //dynamic x and y
header('Content-Type: image/jpeg');

The result of the function is very basic for making the multi-line using imagettftext function will be up to trick otherwise the text will overwrite each other.The code is relatively simple here, I hope you will do the comments 🙂

Comments (6)

  1. Very information and relevant. Thanks for explaining.

  2. Gurmeet Singh says:

    Kindly Check, the example does not work.
    It says, Too few arguments.
    Kindly check and please upload the working code as I need it.

    1. Hi, I have updated code. Please check now

  3. Chethan R T says:

    Hey Bhumi,
    check my code.
    this is simple code compared to yours. In case if you find any flaws do let me know

    This is my code which works:

    function textWithImage($text){
    $im = imagecreatefromjpeg($imagePath);
    $txtColor = imageColorAllocate($im, 255, 255, 255);
    $in = wordwrap($description,50,”|”,true);
    $st = explode(“|”,$in);
    foreach($inStrArr as $key=>$value){
    list($x, $y) = pc_ImageTTFCenter($im, $value, $font, 20,$addOnYVal);
    ImageTTFText($im,20,0, $x, $y, $txtColor, $font, $value);

    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”;


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

    1. Chethan, thanks for sharing your code!!

    2. doesn’t work

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How To Turn On Output Buffering

Posted on 7 years ago


An Introduction to Gulp JS

Posted on 1 year ago


Understanding CSS3 Pseudo-elements

Posted on 3 years ago


How to use WordPress Heartbeat API?

Posted on 3 years ago


Hello world

Updated 1 week ago

Nick Carter

In depth Understanding of Laravel Core

Updated 2 months ago


ECMAScript 6 New Features – 2

Updated 1 year ago


The Reader’s Poll – August 2014

Posted on 4 years ago


The Reader’s Poll – June 2014

Posted on 5 years ago


The Readers’ Poll – May 2014

Posted on 5 years ago