0

I have a few lines of code to generate a plain image with some given text in php. But when I give width for image text goes outside the image. How can I align text inside the image with a fixed width but dynamic height? My code is given below.

header ("Content-type: image/png");
$string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s';                                            
$font   = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate (200,500);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0,  $string, $text_color);
imagepng ($im);

I want this image to automatically adjust texts based on given paragraph. How to do that?

Marko
  • 570
  • 5
  • 21
Joel James
  • 1,315
  • 1
  • 20
  • 37
  • I had so many troubles doing that in an other project because of the letter spacing and each letters width you can't do it in an acceptable way. Instead of creating the image with php, what you can do is, create a simple html file with the text and then use phantomjs to take a screenshot and creating your image in that folder. It will be the easiest way to do that believe me. phantomjs is really easy and can do whatever you're asking in seconds. Here is what you need: http://phantomjs.org/screen-capture.html – artuc Oct 08 '14 at 12:54

1 Answers1

1

You may try this : (based on gannon's contribution at http://php.net/manual/en/function.imagestring.php)

header ("Content-type: image/png");
$string = "Lorem Ipsum is simply dummy\n text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s";
$im = make_wrapped_txt($string, 0, 4, 4, 200);
imagepng ($im);

function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
  if (strlen($color) != 6) $color = 000000;
  $int = hexdec($color);
  $h = imagefontheight($font);
  $fw = imagefontwidth($font);
  $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
  $lines = count($txt);
  $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
  $bg = imagecolorallocate($im, 255, 255, 255);
  $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
  $y = 0;
  foreach ($txt as $text) {
    $x = (($w - ($fw * strlen($text))) / 2); 
    imagestring($im, $font, $x, $y, $text, $color);
    $y += ($h + $space);
  }
  return $im;
}

Giving this kind of result :

enter image description here

Yoric
  • 1,761
  • 2
  • 13
  • 15