PHP 8.5.0 Beta 1 available for testing

Voting

: four minus two?
(Example: nine)

The Note You're Voting On

Somerset Ben
3 years ago
Pushing text around.

I wanted to put various bits of text in the corners of an image so I created a function to accept a location in the image and then put a corner of the text (eg right,top) at that location. Rotation is not supported.

Inputs to the function are fairly standard. The align parameter is two characters R|M|L (right, middle, top)for x alignment and T|M|B (top, middle, bottom) for y alignment; eg "LT" meaning left, top. Omitting the align parameter displays nothing.

The function returns the size of the text block or false indicating failure.

<?php
function imagettfalign (&$im,$size,$x,$y,$col,$font,$text,$align='')
{
$box = imagettfbbox ($size,0,$font,$text) ;
if (!
$box) return false ;
if (
$align)
{
switch (
strtoupper($align[0])) // X position
{
case
'L' : $tX = $x - $box[0] ; break ;
case
'R' : $tX = $x - $box[2] ; break ;
case
'M' : $tX = $x - $box[2]/2 ; break ;
default : return
false ;
}
switch (
strtoupper($align[1])) // Y position
{
case
'B' : $tY = $y - $box[1] ; break ;
case
'T' : $tY = $y - $box[7] ; break ;
case
'M' : $tY = $y - $box[7]/2 ; break ;
default : return
false ;
}
if (!
imagettftext ($im,$size,0,$tX,$tY,$col,$font,$text)) return false ;
}
$r[0]=abs($box[2]) ;
$r[1]=abs($box[7]) ;
return
$r ;
}
?>

An example (excluding font declarations, etc) would be:
<?php
$im
= @imagecreatetruecolor(400,200) ;
$colBlack = imagecolorallocate($im,0, 0, 0);
$xy = imagettfalign ($im,12,200,100,$colBlack,$ttFont,"The middle",'MM') ;
?>

This will show "The middle" smack in the centre of the image.

Finally, apologies for the non-standard indentation. It's just the way I've been doing it for years...

<< Back to user notes page

To Top