ngecoding.com logo

Write Text to Image using TrueType Font in PHP

//if(youLikeIt || itHelpsYou)clickShare();

PHP has several libraries for Image Processing. The most extensively used is GD (Graphics Library).

GD is included by default as of PHP 4.3 wikipedia. So, GD should be used without any additional configuration.


 

GD has two functions to write text to image : 

  1. imagestring  (standard function)

  2. imagettftext  (using TrueType Font, like .ttf or .otf extension).

This codes show you how to write text to image using TrueType Font :

<?php
	//load image
	$imagePath="src/bar.jpg";
	$imgResource = imagecreatefromjpeg($imagePath);
	
	//white text color
	$textcolor = imagecolorallocate($imgResource, 255,255, 255);
	
	$fontPath="src/RobotoSlab-Bold.ttf";
	$fontSize="12";
	$rotation="0";//counter-clockwise rotation
	$x="30";
	$y="25";
	$text="ngecoding.com";
	
	//write text to img
	imagettftext($imgResource, $fontSize, $rotation, 
					$x, $y, $textcolor,$fontPath, 
					$text);
	
	//save image to file
	imagejpeg($imgResource,"src/bar-text.jpg",100);
	
	//output image to browser
	header("Content-Type: image/jpeg");
	imagejpeg($imgResource);
		
	imagedestroy($imgResource);
?>

The result is :

 

//if(youLikeIt || itHelpsYou)clickShare();
//Advertisements
Take a Break //non-technical articles
Hot Topics //most used tags
Email Subscriptions //We won't spam you. Honest!

Enter your email address:

Delivered by FeedBurner