ngecoding.com logo
How to Center a Rotated Text on an Image in PHP

How to Center a Rotated Text on an Image in PHP

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

Sometimes we need to adding rotated text on an image to create Captcha or just for aesthetic needs.

Thanks to GD library for putting this ability yes, but you need to write few lines of code to make it center horizontally and vertically on an image. Especially, if you rotate the text with weird angle such as : 45º, 37º, 287º.

This codes will show you how to center rotated text on an image :

<?php
	//load image
	$imgWidth=200;
	$imgHeight=200;
	$imgResource = imagecreatetruecolor($imgWidth, $imgHeight);
	
	//black background
	$bgcolor = imagecolorallocate($imgResource, 0,0, 0);
	imagefilledrectangle($imgResource, 0, 0, $imgWidth, $imgHeight, $bgcolor);
	
	//white text color
	$textcolor = imagecolorallocate($imgResource, 255,255, 255);
	
	$fontPath="src/RobotoSlab-Bold.ttf";
	$fontSize="18";
	$rotation="45";//counter-clockwise rotation
	$text="ngecoding.com";
	
	//get size of text, to get center coordinate on image
	$textCoords=imagettfbbox($fontSize , $rotation , $fontPath , $text );
	
	$x=  $imgWidth/2 - ($textCoords[4]-$textCoords[0])/2 ;
	$y= $imgHeight/2 - ($textCoords[5]-$textCoords[1])/2;
	
	//write text to img
	imagettftext($imgResource, $fontSize, $rotation, 
					$x, $y, $textcolor,$fontPath, 
					$text);
	
	//save image to file
	imagejpeg($imgResource,"src/rotated-text.jpg",100);
	
	//output image to browser
	header("Content-Type: image/jpeg");
	imagejpeg($imgResource);
		
	imagedestroy($imgResource);
?>

Here are some example outputs :

Rotation: 45º
output of php rotated text 45 degrees
Rotation : 90º
output of php rotated text 90 degrees
Rotation : 135º
output of php rotated text 135 degrees
Rotation : 180º
output of php rotated text 180 degrees
Rotation : 225º
output of php rotated text 225 degrees
Rotation : 270º
output of php rotated text 270 degrees
Rotation : 315º
output of php rotated text 315 degrees
//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