Text wrap for imagettftext

One line text does not always fit into a given width of the picture, then you need to word wrap the text to a new line, depending on the width. If only the width is less than one word, then you will need a shaman's drum and witchcraft. PHP code to create a picture of the text with a given width:

<?php
//content type
header('Content-Type: image/png');

//font
$font = 'arial.ttf';
//font size
$font_size = 10;
//image width
$width = 100;
//text margin
$margin = 5;

//text
$text = "That is why where when why and how, and now why where when why and how?";

//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
	//Create a new text, add the word, and calculate the parameters of the text
	$box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
	//if the line fits to the specified width, then add the word with a space, if not then add word with new line
	if($box[2] > $width - $margin*2){
		$text_new .= "\n".$word;
	} else {
		$text_new .= " ".$word;
	}
}
//trip spaces
$text_new = trim($text_new);
//new text box parameters
$box = imagettfbbox($font_size, 0, $font, $text_new);
//new text height
$height = $box[1] + $font_size + $margin * 2;

//create image
$im = imagecreatetruecolor($width, $height);

//create colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
//color image
imagefilledrectangle($im, 0, 0, $width, $height, $white);

//add text to image
imagettftext($im, $font_size, 0, $margin, $font_size+$margin, $black, $font, $text_new);

//return image
imagepng($im);
//frees any memory associated with image
imagedestroy($im);
This entry was posted in Programming and tagged , , , , .

6 Responses to Text wrap for imagettftext

  1. krasimir

    thank's man for this !

  2. anand

    Good job man....!
    Can you write this code in single line with fix height width we can adjust letter spacing according to text.

  3. This is exactly what I have been looking for. Thanks. I have added it a script I use when I add Founding Father quotes to my site. It will automatically generate a Meme to use for sharing on Facebook, etc. Thanks for sharing your knowledge with the rest of us. You saved me a lot of time.

  4. Thanks!

  5. Alfian

    This is worked like a charm! nice thx..

  6. New name

    Thank you very much

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.