Centering multiple lines of text using GD and PHP

I am trying to print a few lines of text on an image and center them.

i.e.

      This is a line with text.

Now I have only the left position for the entire line. Any shortcuts on how this works? I think it could be getttfbox on the whole line, then the line breaks, and then centers the new text inside this larger ttfbox. This is a pain in the ass ...

EDIT: Made up 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 line of $ is an array with some information about how and what to print. Hope that helps someone.

+5
source share
4 answers

You can use the 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:

demo

+4

, imagettfbbox, , , , , .

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);
}

: PHP...

. , , $angle . $width - .

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;
}
+2

You can use the excellent gd-text library . If you use a composer, an example would be:

<?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);
+1
source

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

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

Tell me if this works because I have never tried this.

-1
source

All Articles