Text to Image PHP Script – Demo and Download

In this post we are going to see how to change any TEXT or STRING to PNG image using PHP. PHP comes with an image processing library called GD library. This has many features like creating an image, drawing a TEXT, giving color to the text, making transparent etc., there are plenty of function and those are really easy to understand and write programs.

GD library has to be installed in your Apache server to make this script work!.

Following things you can learn from today’s script (respective functions are written in parentheses):

1. Creating an Image – ( imagecreatetruecolor(); )
2. Finding the bounds for the image – ( ImageTTFBBox() )
3. How to fill the color to the text – ( imagettftext() )
4. How to fill the background color to the text – ( imagefilledrectangle() )
5. Rendering the PNG image on browser – ( imagepng() )

To render an PNG image on browser. The header should be change to image/png.

Here is the script:

//change the header to image
header ("Content-type: image/png");
//give the font file
$font = 'arial.TTF';
//set the font size
$font_size = 50;
$string = $_POST['string'];

// get the font height.
$bounds = ImageTTFBBox($font_size, 0, $font, "W");

$font_height = abs($bounds[7]-$bounds[1]);

// determine bounding box. this helps to keep the size of the image according to the text
$bounds = ImageTTFBBox($font_size, 0, $font, $string);
	$width = abs($bounds[4]-$bounds[6]);
	$height = abs($bounds[7]-$bounds[1]);
	$offset_y = $font_height;
	$offset_x = 0;

//create image
$img = imagecreatetruecolor($width+(2)+1,$height+(2)+1) or die("Cannot Initialize new GD image stream");

//fill the text color
$r=1; $g=150; $b=150;
$text_color = imagecolorallocate($img, $r, $g, $b);

//Draw the string
$bg_r = 255; $bg_g = 255; $bg_b = 65;
$bgcolor = imagecolorallocate($img, $bg_r, $bg_g, $bg_b);
imagefilledrectangle($img, 0, 0, $width+(2)+1, $height+(2)+1, $bgcolor);
imagettftext($img, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $string);

//Output the image

<h1>Text to Image using PHP by <a href="blog.theonlytutorials.com">Blog.Theonlytutorials.com</a></h1>
	<form action="" method="post">
		Enter the text <input type="text" name="string" />

Here it the demo and download:



3 thoughts on “Text to Image PHP Script – Demo and Download

  1. hello sir,
    i’m new in php. how to use the tamil language on the image using imagettftext method i tried many way i’ts not working .
    please give me any clue are guide me sir. .

Leave a Reply

Theme: Overlay by Kaira
%d bloggers like this: