Reputation: 12487
I'm using imagemagick to put some text on an image but I'm struggling with finding a way to dynamically put the text bang in the middle of the box.
For bonus points, is there also a way to then offset it with a second command, i.e nudge it 50px right of centre. This is because usually I want the text to be in the middle unless they add a picture, then I need to make space for the picture too.
The text and font-size will be variable, but still needs to be centered.
This is my current code:
<?php
function process($inputdata)
{
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );
/* New image */
$image->newImage(400, 300, $pixel);
/* Black text */
$draw->setFillColor('black');
/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );
/* Create text */
$image->annotateImage($draw, 10, 45, 0, $inputdata);
/* Give image a format */
$image->setImageFormat('png');
/* Output the image with headers */
header('Content-type: image/png');
echo $image;
return;
}
I tried adding this command, but it didn't seem to have any effect:
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
The closest answer I could find is this one, but it seems a bit long winded to have to calculate the size and then centre it that way.
Upvotes: 1
Views: 2770
Reputation: 207465
This works fine for me:
#!/usr/local/bin/php -f
<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );
/* New image */
$image->newImage(400, 300, $pixel);
/* Black text */
$draw->setFillColor('black');
/* Font properties */
$draw->setFontSize( 30 );
$draw->setGravity(Imagick::GRAVITY_CENTER );
/* Create text */
$image->annotateImage($draw, 0, 0, 0, "Some funky text");
/* Give image a format */
$image->setImageFormat('png');
$image->writeImage('result.png');
?>
Upvotes: 6