Share on Google+Share on Google+

PHP GD center text

Advertisement
This example shows how to add text to center of an image in php gd.

<?php

$width = 400;

$height = 100;

$im = ImageCreate($width, $height);

$bg = ImageColorAllocate($im, 255, 255, 255);

$border = ImageColorAllocate($im, 255, 0, 0);

ImageRectangle($im, 0, 0, $width - 1, $height - 1, $border);

$text = 'This is the text which is center of image.';

$textcolor = ImageColorAllocate($im, 255, 0, 0);

$font = 3;

 

$font_width = ImageFontWidth($font);

$font_height = ImageFontHeight($font);

$text_width = $font_width * strlen($text);

$position_center = ceil(($width - $text_width) / 2);

$text_height = $font_height;

$position_middle = ceil(($height - $text_height) / 2);

$image_string = ImageString($im, $font, $position_center, $position_middle, $text, $textcolor);

header("Content-type: image/jpeg");

Imagejpeg($im);

?>

After running the program you will get the following output

Advertisements

Posted on: November 3, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.