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.

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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);

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.