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.

// Create the image
$im = imagecreatetruecolor(600, 400);
 
// Create some colors
$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)';
 
// Replace path by your own font path
$font = 'MotionPicture_PersonalUseOnly.ttf';
 
// Add some shadow to the text
//imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
 
// Add the 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
// Set the content-type
header('Content-Type: image/png');
 
// Create the image
$im = imagecreatetruecolor(600, 400);
 
// Create some colors
$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);
 
// The text to draw
$text = 'Rohit Kumar (My Public Notebook)';
// Replace path by your own font path
$font = 'MotionPicture_PersonalUseOnly.ttf';
 
// Add some shadow to the text
//imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
 
// Add the text
imagettftext($im, 40, 0, 20, 70, $white, $font, $text);
 
// Using imagepng() results in clearer text compared with imagejpeg()
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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.