Jump to content

GD: Putting Text in the Center of the image?


eugeniu

Recommended Posts

Possibly build the text as a separate image, find the new width and height of your TEXTONLY image.  From there determine the remaining space on your image, (Total width - textonly width) & (total heigh-textonly height).  From there you could divide those each by 2, and offset from the center of the image.  Meaning paste the textonly image onto the background 200x30 png, and position the text only using the values as coords as I said above.

why would you need a alternative? our 2 suggestions work just fine...

 

Your suggestion would make the image like this:

 

|                            |

|              hello world|

|                            |

 

Only starting at the center.

eugeniu,

First off:  Be grateful people are even trying to help you.  No one here is under any obligation to do anything for you.  The mere fact that you don't like what we suggest should never get in front of your courtesy and respect to people that try to help you.  That being said, having never used GD before, I googled and phpmanualed for an hour and made this:

 

GD centered image Refresh to see different strings.

 

It's kinda funny, I followed my the suggestions by ACE and myself, and it worked out, go figure.  All it took was a little elbow grease.

Before you complain that this doesn't fit your exact needs, STOP.  I am showing you that it can be done at a basic level, any additions you make need to be compensated for accordingly.  It's not my job to code for you.  I just happen to like challenges, like making this, for instance.

 

relevant code

<?php
  $width = 200; // SET IMAGE WIDTH
  $height = 30; // SET IMAGE HEIGHT
   $font_size = 2;  // MY FONT SIZE
   $text_width = imagefontwidth($font_size) * $x;  // TEXT WIDTH = FONTWIDTH * AMOUNT OF LETTERS IN STRING ($x = STRLEN($string));
   $text_height = imagefontheight($font_size); // TEXT HEIGHT IS JUST THE FONT HEIGHT


$im = imagecreate($width, $height);//create base image
  $bg = imagecolorallocate($im, 255, 255, 255);//white bg for base
  $txt = imagecolorallocate($im, 75, 75, 75);//black text

$offsetH = ((($height-1)-$text_height) / 2);
// my font is off by 1 pixel, that's why i have -1.  I take the total height(30) -1= 29 - font height
// I divide all that by 2, because we only offset from one side

$offsetW = (($width-$text_width) / 2);
// width is total width (200) subtract width of text put together
// divide by two to offset from one side

  imagestring($im, $font_size, $offsetW, $offsetH, $string, $txt);//add string accordingly
    
    imagepng($im,'image.png');//create the image


//Die image die.
    imagedestroy($im);
?>

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.