Some of the cases we need to create an image dynamically when the web page is loading, Then a question raised in the mind - Can I convert text to image in PHP? the answer is Yes! why not. For doing this activity you just need to do a few steps. These steps are given below:
- Check your GD library extension is on in your current PHP version.
- If it does not enable simply just un-comment it.
- Include phpTextToImage class in your project.
- Create an object of this class.
- Call create image function with your text.
- Call save function with your file name and location.
This library has numbers of features which fulfill your all requirement, these features are given:
- Create dynamically text image.
- Set your text font.
- Choose an image background.
- Set your text color also.
- Adjust your image height and width.
Let's start with the example. First of all, include the phpTextToImage class in your project files.
Convert Text to Image in PHP with GD
The process has two separate parts: preparing a blank canvas and drawing text on that canvas. The GD extension supplies the image functions, while the TrueType font file controls the appearance of the letters. After the drawing is complete, PHP can send the image directly to the browser or write it to a file.

Before testing the class, confirm that GD is available in the PHP runtime used by your web server. A command-line PHP installation and the PHP installation used by Apache or PHP-FPM can have different extensions enabled. Checking the correct runtime avoids a situation where the code works locally but fails after deployment.
Choose the Output Format Carefully
PNG is a good default when the image contains sharp text, flat colors, or transparency. JPEG is useful for photographic backgrounds, but compression can soften small lettering. The class in this tutorial provides both saveAsPng() and saveAsJpg(), so you can choose the format based on the design rather than using one format for every image.
Keep the generated filename predictable and never build a filesystem path directly from untrusted user input. If visitors supply the text, validate its length and remove control characters before drawing it. A short limit also prevents unexpectedly wide or tall output and keeps server-side processing manageable.
Verify the Font and Write Permissions
The example uses a TrueType font path. That file must exist relative to the script or be replaced with an application path. If the font cannot be found, functions that measure or draw text may fail even though GD itself is installed.
The destination directory must also be writable by the PHP process. A successful image resource does not guarantee that imagepng() or imagejpeg() can save a file. Check the return value of the save function and log the failure rather than displaying server paths to visitors.
Plan for Long Text
The sample centers each line, but it does not automatically wrap a long paragraph. For user-generated text, split it into lines before calling imagettfbbox() and imagettftext(). Measure each candidate line against the image width, then move to the next line when it would exceed the available space.
- Reserve horizontal and vertical padding around the text.
- Use readable contrast between foreground and background colors.
- Normalize text before it is placed in surrounding HTML.
- Destroy large image resources after saving when many images are created.
- Return a clear error when the font or destination directory is unavailable.
For related server-side examples, see this guide to convert a multidimensional array to XML in PHP and the article about PHP exception handling.
<?php
/**
* phpTextToImage class
* This class converts text to image in PHP
*
* @author Legend Blogs
* @link https://www.legendblogs.com
*/
class phpTextToImage {
private $image;
/**
* Create image from text
* @param string text to convert into image
* @param string textColor
* @param string backgroundColor
* @param int font size of text
* @param int width of the image
* @param int height of the image
*/
function createImage($text, $textColor = '', $backgroundColor = '', $fontSize = 22, $imgWidth = 600, $imgHeight = 300) {
//text font path
$font = 'font/Pacifico-Regular.ttf';
//create the image
$this->image = imagecreatetruecolor($imgWidth, $imgHeight);
$colorCode = array('#ffffff','#db3236', '#f4c20d', '#3cba54', '#4c53cc', '#56aad8', '#61c4a8');
if ($backgroundColor == '') {
/* select random color */
$backgroundColor = $this->hexToRGB($colorCode[rand(0, count($colorCode) - 1)]);
} else {
/* select background color as provided */
$backgroundColor = $this->hexToRGB($backgroundColor);
}
if ($textColor == '') {
/* select random color */
$textColor = $this->hexToRGB($colorCode[rand(0, count($colorCode) - 1)]);
} else {
/* select background color as provided */
$textColor = $this->hexToRGB($colorCode[rand(0, count($textColor) - 1)]);
}
$textColor = imagecolorallocate($this->image, $textColor['r'], $textColor['g'], $textColor['b']);
$backgroundColor = imagecolorallocate($this->image, $backgroundColor['r'], $backgroundColor['g'], $backgroundColor['b']);
imagefilledrectangle($this->image, 0, 0, $imgWidth - 1, $imgHeight - 1, $backgroundColor);
//break lines
$splitText = explode("\\n", $text);
$lines = count($splitText);
$angle = 0;
foreach ($splitText as $txt) {
$textBox = imagettfbbox($fontSize, $angle, $font, $txt);
$textWidth = abs(max($textBox[2], $textBox[4]));
$textHeight = abs(max($textBox[5], $textBox[7]));
$x = (imagesx($this->image) - $textWidth) / 2;
$y = ((imagesy($this->image) + $textHeight) / 2) - ($lines - 2) * $textHeight;
$lines = $lines - 1;
//add the text
imagettftext($this->image, $fontSize, $angle, $x, $y, $textColor, $font, $txt);
}
return true;
}
/* function to convert hex value to rgb array */
protected function hexToRGB($colour) {
if ($colour[0] == '#') {
$colour = substr($colour, 1);
}
if (strlen($colour) == 6) {
list( $r, $g, $b ) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
} elseif (strlen($colour) == 3) {
list( $r, $g, $b ) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
} else {
return false;
}
$r = hexdec($r);
$g = hexdec($g);
$b = hexdec($b);
return array('r' => $r, 'g' => $g, 'b' => $b);
}
/**
* Display image
*/
function showImage() {
header('Content-Type: image/png');
return imagepng($this->image);
}
/**
* Save image as png format
* @param string file name to save
* @param string location to save image file
*/
function saveAsPng($fileName = 'text-image', $location = '') {
$fileName = $fileName . ".png";
$fileName = !empty($location) ? $location . $fileName : $fileName;
return imagepng($this->image, $fileName);
}
/**
* Save image as jpg format
* @param string file name to save
* @param string location to save image file
*/
function saveAsJpg($fileName = 'text-image', $location = '') {
$fileName = $fileName . ".jpg";
$fileName = !empty($location) ? $location . $fileName : $fileName;
return imagejpeg($this->image, $fileName);
}
}
Now, create your project file where you want to create the image of your text dynamically, and just include class and create an object like this:
//include phpTextToImage class
require_once 'phpTextToImage.php';
//create img object
$img = new phpTextToImage;
After that, simply use this $img object to create your image with createImage function:
$text = 'Welcome to Legend Blogs.\nConvert Text To Image In PHP.';
$img->createImage($text);
If you want to save the image in your physical location you just need to call a saveAsPng() or saveAsJpg() function with your filename and location:
$fileName = "legendblogs";
$img->saveAsPng($fileName);
Your final code is:
<!DOCTYPE html>
<?php
//include phpTextToImage class
require_once 'phpTextToImage.php';
//create img object
$img = new phpTextToImage;
?>
<html lang="en">
<head>
<title>Convert Text To Image In PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="text-danger">Convert Text To Image In PHP</h2>
<h4>Refresh Your Page To Change Color</h4>
<?php
//create image from text
$text = 'Welcome to Legend Blogs.\nConvert Text To Image In PHP.';
$img->createImage($text);
//display image
$fileName = "legendblogs";
$img->saveAsPng($fileName);
?>
<img src="<?php echo $fileName; ?>.png" />
</div>
</body>
</html>
The output of the given text:

1 Comment
Braulio
Hi, bro! thanks it is working fine!
How can I use an array of many images?
Thanks.
Write a comment