PHP GD center text


 

PHP GD center text

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

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

Ads