Create an image and add text on it using php gd library

PHP is a great language with powerful library and functions, There is lot’s of predefined functions which help us lot during development of the website, In this tutorial we are going to use one of the best php library to create image dynamically with some text.



Creating dynamic image is a great idea if you don’t want to host so many images on web you can create images using PHP gd libraray and also do lot more image customization things. You can crop adjust size and resolution of the image dynamically.
create-image-php-gd-1
Fist of all check GD support is enabled or not by running below function on web.

phpinfo();

create-image-php-gd
If php gd extension is not enabled then first enable it.

Next set page header content type as image

header('Content-Type: image/png');

Create image with defined height and width and also create some colors for background and text font.


$im = imagecreatetruecolor(600, 400);
 

$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$imgbg = imagecolorallocate($im, 255, 100, 100);
imagefilledrectangle($im, 0, 0, 600, 400, $imgbg);

Define text and font style, you can download different different font style from internet and make text stylish.

$text = 'Rohit Kumar (My Public Notebook)';
 

$font = 'MotionPicture_PersonalUseOnly.ttf';
 

//imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
 

imagettftext($im, 40, 0, 20, 70, $white, $font, $text);

Finally add text on image by imagettftext php gd function.

imagettftext($im, 40, 0, 20, 70, $white, $font, $text);




Final code will be..

img.php

<?php

header('Content-Type: image/png');
 

$im = imagecreatetruecolor(600, 400);
 

$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$imgbg = imagecolorallocate($im, 255, 100, 100);
imagefilledrectangle($im, 0, 0, 600, 400, $imgbg);
 

$text = 'Rohit Kumar (My Public Notebook)';

$font = 'MotionPicture_PersonalUseOnly.ttf';
 

//imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
 

imagettftext($im, 40, 0, 20, 70, $white, $font, $text);
 

imagepng($im);
imagedestroy($im);
?>

Hope this example will help you to generate and add text on image using php gd library.

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Posted in PHP