Write the text on image using GD Library

December 30, 2010 | In: GD Library, php, web development

What is the GD library? GD is an open source code library for the dynamic creation of images by programmers. GD is written in C, and “wrappers” are available for Perl, PHP and other languages. GD creates PNG, JPEG and GIF images, among other formats. GD is commonly used to generate charts, graphics, thumbnails, and most anything else, on the fly. While not restricted to use on the web, the most common applications of GD involve website development. You can learn more from http://www.boutell.com/gd/.

In most case we need to show some random text on the site in different directions but we can not do this by using CSS. Then we need GD library. Here I am giving an example to show a text on the JPG and PNG image in rotate direction.

function write_text_on_image($imageType, $image_path, $string = 'naveenos')
{
switch($imageType) {
	case "jpg":
	case "jpeg":
		header("Content Type: image/jpeg");
		// Create the image
		$img = imagecreatefromjpeg($image_path); 
 
		// Create some colors
		$white = imagecolorallocate($img, 255, 255, 255);
		$grey  = imagecolorallocate($img, 128, 128, 128);
		$black = imagecolorallocate($img, 0, 0, 0);
 
		// The text to draw
		$text = $string;
 
		// Replace path by your own font path OR put this font in your folder
		$font = 'arial.ttf';
 
		// Add the text
		imagettftext($img, 30, 10, 61, 111, $grey, $font, $text);
		imagejpeg($img, 'image/new_image.jpg');
	break;
 
	case "png";
		header("Content Type: image/png");
		// Create the image
		$img = imagecreatefrompng($image_path); 
 
		// Create some colors
		$white = imagecolorallocate($img, 255, 255, 255);
		$grey  = imagecolorallocate($img, 128, 128, 128);
		$black = imagecolorallocate($img, 0, 0, 0);
 
		// The text to draw
		$text = $string;
 
		// Replace path by your own font path OR put this font in your folder
		$font = 'arial.ttf';
 
		// Add the text
		imagettftext($img, 12, 10, 61, 111, $grey, $font, $text);
 
		// Using imagepng() results in clearer text compared with imagejpeg()
		imagepng($img, 'image/png_image.png');
	break;
	}
}
write_text_on_image("jpeg", "image/ns.jpg", "naveenos");
// Call below function to write text on PNG image.
//write_text_on_image("png", "image/ns.png", "naveenos");

That’s it.. It will create a new image with your given new image name.
According to my example it will show the output like: