Hey People,

Wonder how could you insert line breaks, or make your string wrappable when you are creating images on the fly in php. I bet before you hopped in here, you must have tried inserting \n,\r,<br> using function wordwrap(); However its slightly different and the strings on images are not the way the usual strings work.

So here is how we go about wrapping string in images. I would like you to see this code snippet and then read the explanation given below it.

$text='The quick brown fox was so long but it still jumped over the lazy dog.';
$im = @imagecreate(300, 150); //creates an image
$background_color = imagecolorallocate($im, 0, 0, 0); //sets image background color
$y=5; //vertical position of text
foreach($arrText as $arr)
  $white=imagecolorallocate($im,255,255,255); //sets text color
  imagestring($im,5,15,$y,trim($arr),$white); //create the text string for image,added trim() to remove unwanted chars
header("Content-type: image/png");

The second line of the script plays the real trick here. We first wrapped the long string with newline character(\n), to our convenience say 20 characters. In the same statement, exploded this string to output an array which picks the parts of strings which are broken by the newline character(\n). So this way we have an array which has the subparts of the main string. Next we create an image of the size 300x150px, and set its background color as black using the function imagecolorallocate.

Now the main steps is this foreach iteration, which creates image strings on the fly using the substring array which we created in line number 2 of the script. We set the color of the string as white using the same function called imagecolorallocate. Everytime the loop is executed for the iteration, the imagestring function creates an image string, whose vertical position is changed by the variable $y. I have used a change of 15px vertically, you can change the value as per your requirement. You can also change the value for horizontal placement of the string and that is by changing the value of 3rd parameter of the function imagestring, just like we are doing it for vertical placement of the text.

In the end when all the array is parsed, loop terminates and image is rendered. The output of the above script is :


Hope that helps but still if you got any doubt, just leave a comment. You can also subscribe to our RSS feeds to read more posts like this.

Stay Digified !!
Sachin Khosla

Share this post: