Carol.Kar
Carol.Kar

Reputation: 5355

Image-Workshop: Center text within image

I am using PHP 7.1.33 and "sybio/image-workshop": "^2.1" - PHPImageWorkshop - to create/modify images.

I am currently generating the image as the following:

<?php

require_once 'vendor/autoload.php';

use PHPImageWorkshop\ImageWorkshop;

$layer = ImageWorkshop::initFromPath(__DIR__.'\images\bank.jpg');

$layer->applyFilter(IMG_FILTER_CONTRAST, 40, null, null, null, true); // constrast
$layer->applyFilter(IMG_FILTER_BRIGHTNESS, 10, null, null, null, true); // brightness

// apply text
$text = "This is a test text";
$date = date("Y-m-d");

$font = 5; // Internal font number (http://php.net/manual/en/function.imagestring.php)
$color = "ffffff";
$positionX = 0;
$positionY = 0;
$align = "horizontal";

$layer->writeText($text, $font, $color, $positionX, $positionY, $align);

// Saving / showing...
$layer->save(__DIR__.'/output/', 'bank.jpg', true, null, 95);

And I get the following output:

enter image description here

However, I would like to get:

enter image description here

Any suggestions how to specifiy the font and center the text in a large font size in the middle?

I appreciate your replies!

Upvotes: 0

Views: 237

Answers (2)

naszy
naszy

Reputation: 511

Create a new text layer and then place it on top of the existing layer. The key is the 'MM' parameter which does the centering.

$font = '/path/to/font.ttf';
$size = 100;
$color = "ffffff";
$align = "horizontal";

$textLayer = ImageWorkshop::initTextLayer($text, $font, $size, $color, 0, 0);
$layer->addLayer(1, $textLayer, 0, 0, 'MM');

Also, you can set the font size with the $size variable.

Upvotes: 1

AWS PS
AWS PS

Reputation: 4710

You need to get Layer dimensions first and then divide it by 2

$width = $layer->getWidth(); // in pixel
$height = $layer->getHeight(); // 

$positionX = int($width / 2) ;
$positionY = int($height / 2) ;

$layer->writeText($text, $font, $color, $positionX, $positionY, $align);

Upvotes: 1

Related Questions