Jump to content

GD and imagettftext() - center variable length string


Beauford

Recommended Posts

I am trying to add text to an image, which I have done. The problem is this. The length of the text will be different each time, so I need to have it so it is centered regardless of the length of the string. I have read a bunch of things and tried several things I found, but nothing is working.

 

The font is always going to be the same, so I don't need to worry about that, but I know capitals and lowercase are going to be different sizes and need to be taken into account.

 

Can this be done with imagettftext(), or is there another function that would be better suited. I am completely new to GD so be gentle.

 

Any help is appreciated.

 

The image will always be 800 by 600.

 

 

 

Yeah, that will give the info needed to calculate the width of the text. Then, it's just

((image width) - (text width)) / 2

to get the x offset you need when writing the text to the image

read what the function does it returns dimensions of a box not a text box.

 

Which means what in relation to what I need. As I said, I have never used any GD stuff, so I have no idea what any of it does.

 

All I want is to center some text on an image.

 

THX

Try this:

<?php

$text = "Center This Text!";
$image = "image.jpg"; 
$font = "arial.ttf";
$font_size = "25";

$image_2 = imagecreatefromjpeg($image);
$black = imagecolorallocate($image_2,0,0,0);

$image_width = imagesx($image_2);  
$image_height = imagesy($image_2);

$text_box = imagettfbbox($font_size,$angle,$font,$text);
$text_width = $text_box[2]-$text_box[0]; // lower right corner - lower left corner
$text_height = $text_box[3]-$text_box[1];

$x = ($image_width/2) - ($text_width/2);
$y = ($image_height/2) - ($text_height/2);

imagettftext($image_2,$font_size,0,$x,$y,$black,$font,$text );

header ("Content-type: image/png");
imagejpeg($image_2);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.