'Imagick center (horizontal, vertical)

I want to center text over an image, horizontal and vertical. And let it automatically fit (unless what the content is).

When I use the command line, this command works almost perfectly (needs some little finetuning):

magick image.jpg -gravity Center -size 320x140 caption:'This text is resized to best fill the space given.' -compose over -composite ouput.jpg

Command line output

However, now I want to achieve the same with PHP, but the text does not resize over multiple lines, so I am doing something wrong.

The script I've created so far:

$text = 'This text is resized to best fill the space given.';
$width = 600;
$height = 600;

$textBackground = new ImagickPixel('transparent');
$textColor = new ImagickPixel('#000');

$gradient = new Imagick('image.jpg');

$image = new Imagick();
$image->newImage($width, $height, $textBackground);

$gradient->setImageColorspace($image->getImageColorspace());

$draw = new ImagickDraw();
//$draw->setFillColor($textColor);
$draw->setFontSize( 36 );
$draw->setFont("Alegreya.ttf");
$draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 0, 0, 0, $text);

$gradient->compositeImage($image, Imagick::COMPOSITE_OVER, 0, 0);
$gradient->setImageFormat('jpg');

header('Content-type: image/jpg');
echo $gradient;

The output this generates:

Bad output



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source