Convert Text To Image In PHP (Simple Step-By-Step Guide)

Welcome to a tutorial on how to convert text to image in PHP. Need to output some text as an image? Maybe to stop some nasty users from copying sensitive text?

An easy way to convert text to image in PHP is to use the GD library, and the steps are:

  1. Create an empty canvas – $img = imagecreate(500, 300);
  2. Define the colors.
    • $white = imagecolorallocate($img, 255, 255, 255);
    • $black = imagecolorallocate($img, 0, 0, 0);
  3. Fill a solid rectangle – imagefilledrectangle($img, 0, 0, 500, 300, $white);
  4. Draw the text onto the image – imagestring($img, 5, 0, 0, "TEXT", $black);
  5. Save the image to a file – imagepng($img, "IMAGE.png");

This simple snippet covers the basics, but let us walk through a few more examples in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Text To Image Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

QUICK NOTES

  • Please make sure that the GD extension is enabled in the php.ini file – extension=gd or extension=gd2.
  • In 3-font.php and 4-center.php, change $font = "C:\Windows\Fonts\arial.ttf" to your own. Take note that PHP needs to have read permission to the font file to properly use it.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

TEXT TO IMAGE WITH PHP GD

All right, let us now go into more examples of writing text using the GD extension in this section.

 

EXAMPLE 1) BASIC TEXT TO IMAGE

1-basic.php
<?php
// (A) NEW EMPTY IMAGE OBJECT
// imagecreate(WIDTH, HEIGHT)
$img = imagecreate(150, 80);
 
// (B) SET COLORS
// imagecolorallocate(IMAGE, RED, GREEN, BLUE)
$red = imagecolorallocate($img, 255, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);
 
// (C) EMPTY RED RECTANGLE
// imagefilledrectangle(IMAGE, START X, START Y, END X, ENDY, COLOR)
imagefilledrectangle($img, 0, 0, 150, 80, $red);
 
// (D) WRITE TEXT
// imagestring(IMAGE, FONT, X, Y, TEXT, COLOR)
// FONT is a number 1 to 5. 1 is smallest font size, 5 is biggest.
imagestring($img, 5, 10, 10, "FOO BAR!", $white);
 
// (E) SAVE TO FILE
// imagepng(IMAGE, TARGET FILE)
imagepng($img, "demo.png");
imagedestroy($img); // OPTIONAL

As in the snippet in the introduction, creating a text image in PHP is kind of long-winded:

  1. imagecreate() creates an empty canvas. Yes, take note, an empty transparent image.
  2. Specify the colors to use in the image.
  3. Use imagefilledrectangle() to fill a solid rectangle.
  4. Then, use imagestring() to write the text onto the image.
  5. Finally, imagepng() to save the image into a file. It is optional to use imagedestroy() to clear the image, but good for cleaning up in big projects nonetheless.

 

 

EXAMPLE 2) VERTICAL TEXT & OUTPUT TO SCREEN

2-vertical.php
<?php
// (A) NEW EMPTY IMAGE OBJECT
$img = imagecreate(80, 150);
 
// (B) SET COLORS
$green = imagecolorallocate($img, 0, 255, 0);
$black = imagecolorallocate($img, 0, 0, 0);
 
// (C) EMPTY GREEN RECTANGLE
imagefilledrectangle($img, 0, 0, 150, 80, $green);
 
// (D) WRITE TEXT
imagestringup($img, 5, 10, 100, "FOO BAR!", $black);
 
// (E) OUTPUT
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

This is pretty much the same, but with 2 differences:

  • We are using imagestringup() to write the text now – This one simply writes the font in a vertical manner.
  • Instead of saving to a file, we directly output an image HTTP header header('Content-type: image/png') and use imagepng($img) to serve the image data.

 

 

EXAMPLE 3) DEFINING FONT TO USE

3-font.php
<?php
// (A) NEW EMPTY IMAGE OBJECT
$img = imagecreate(150, 80);
 
// (B) SET COLORS
$blue = imagecolorallocate($img, 0, 0, 255);
$white = imagecolorallocate($img, 255, 255, 255);
 
// (C) EMPTY BLUE RECTANGLE
imagefilledrectangle($img, 0, 0, 150, 80, $blue);
 
// (D) WRITE TEXT
$txt = "FOO BAR";
$font = "C:\Windows\Fonts\Arial.ttf"; // ! CHANGE THIS TO YOUR OWN !
// imagettftext(IMAGE, FONT SIZE, ANGLE, X, Y, COLOR, FONT, TEXT)
imagettftext($img, 24, 5, 5, 55, $white, $font, $txt);
 
// (E) OUTPUT
/* WE CAN ALSO OUTPUT IN JPEG
* header('Content-type: image/jpeg');
* imagejpeg($img)
*/
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

We are just using imagettftext() to write the text now – This one has more “controls” over which font to use, we can also set the font size and angle with it.

 

 

EXAMPLE 4) CENTERING TEXT ON IMAGE

4-center.php
<?php
// (A) SETTINGS
$txt = "FOO BAR!";
$font = "C:\Windows\Fonts\arial.ttf"; // ! CHANGE THIS TO YOUR OWN !
$font_size = 24;
$font_angle = 0;
$width = 300;
$height = 150;
 
// (B) IMAGE OBJECT + COLORS
$img = imagecreate($width, $height);
$grey = imagecolorallocate($img, 200, 200, 200);
$black = imagecolorallocate($img, 0, 0, 0);
imagefilledrectangle($img, 0, 0, $width, $height, $grey);
 
// (C) TEXT BOX SIZE
// imagettfbbox(FONT SIZE, ANGLE, FONT, TEXT)
$text_size = imagettfbbox($font_size, $font_angle, $font, $txt);
$text_width = max([$text_size[2], $text_size[4]]) - min([$text_size[0], $text_size[6]]);
$text_height = max([$text_size[5], $text_size[7]]) - min([$text_size[1], $text_size[3]]);
 
// (D) CENTERING THE TEXT BLOCK
$centerX = CEIL(($width - $text_width) / 2);
$centerX = $centerX<0 ? 0 : $centerX;
$centerY = CEIL(($height - $text_height) / 2);
$centerY = $centerY<0 ? 0 : $centerY;
imagettftext($img, $font_size, $font_angle, $centerX, $centerY, $black, $font, $txt);
 
// (E) OUTPUT
imagepng($img, "demo.png");
imagedestroy($img);

Centering a block of text is very Mathematical… But in essence, we have to use imagettfbbox() to get the bounding box around the text. This will return an array of 8 numbers, each corresponding to a coordinate of the text box.

Then, we can determine the width and height of the text box using the coordinates:

  • $text_width = (2 OR 4, WHICHEVER IS FURTHER RIGHT) - (0 OR 6, WHICHEVER IS FURTHER LEFT).
  • $text_height = (5 OR 7, WHICHEVER IS FURTHER UP) - (1 OR 3, WHICHEVER IS FURTHER DOWN).

Finally, use this to calculate the center placement on the image:

  • $centerX = (IMAGE WIDTH - TEXT WIDTH) / 2.
  • $centerY = (IMAGE HEIGHT - TEXT HEIGHT) / 2.

 

 

USEFUL BITS & LINKS

That’s it for the simple script, and here are some small extras and links that may be useful to you.

 

FONT COPYRIGHT WARNING

Yes, we can specify which font to use, but please do not go on a download frenzy and use whatever fonts on the Internet. That is because some fonts are still subjected to copyright, and they cannot be used for commercial purposes… Always remember to check the usage license before you use it in your own projects.

 

THE SUMMARY

Function Description Reference Link
imagecreate(WIDTH, HEIGHT) Create a new empty canvas. Click Here
imagecolorallocate(IMAGE, RED, GREEN, BLUE) Specify a color code to use on the canvas. Click Here
imagefilledrectangle(IAMGE, X1, Y1, X2, Y2, COLOR) Fill a solid rectangle. Click Here
imagestring(IMAGE, SIZE - 1 to 5, X, Y, TEXT, COLOR) Write text to the image using the built-in font. Click Here
imagecreateup(IMAGE, SIZE - 1 to 5, X, Y, TEXT, COLOR) Write vertical text to the image using the built-in font. Click Here
imagettftext(IMAGE, SIZE, ANGLE, X, Y, FONT, TEXT) Write text to the image (with more controls). Click Here
imagettfbbox(SIZE, ANGLE, FONT, TEXT) Get the size of the text box. Click Here
imagepng(IMAGE, FILE) Save the given image – If  FILE is not present, will directly output the data. Click Here
imagejpeg(IMAGE, FILE, QUALITY 1-100) Save the given image. Click Here
imagedestroy(IMAGE) Destroy the given image. Click Here

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

 

INFOGRAPHIC CHEATSHEET

Write Text To Image In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope that it has helped you with your project, and do you have more creative uses for turning text into images? Please do share them in the comments below. Good luck and happy coding!

3 thoughts on “Convert Text To Image In PHP (Simple Step-By-Step Guide)”

  1. and the reverse? what it would be like to extract text from an image for inputs, for example upload an image mseja from the web cam or library and the system extract numbers and place in various inputs

  2. Thank you so much. I really needed this type of resolution. It is simple, easy to understand, and straight to the point. Your a life saver!

Leave a Comment

Your email address will not be published. Required fields are marked *