- Convert Text To Image In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- TEXT TO IMAGE WITH PHP GD
- EXAMPLE 1) BASIC TEXT TO IMAGE
- EXAMPLE 2) VERTICAL TEXT & OUTPUT TO SCREEN
- EXAMPLE 3) DEFINING FONT TO USE
- EXAMPLE 4) CENTERING TEXT ON IMAGE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- WRITING MULTIPLE LINES?
- FONT COPYRIGHT WARNING
- THE SUMMARY
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEATSHEET
- THE END
- How to Convert Text to Image using PHP
- Get and Validate Text Input via HTML Form
- Converting Text to an Image using PHP GD functions
- Convert Text to Image in PHP
- TextToImage Class
- Convert Text String to Image in PHP
- Conclusion
Convert Text To Image In PHP (Simple Examples)
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?
- Create an empty canvas – $img = imagecreate(500, 300);
- Define the colors.
- $white = imagecolorallocate($img, 255, 255, 255);
- $black = imagecolorallocate($img, 0, 0, 0);
- Fill a solid rectangle background – imagefilledrectangle($img, 0, 0, 500, 300, $white);
- Draw the text – imagestring($img, 5, 0, 0, «TEXT», $black);
- Save the image to a file – imagepng($img, «IMAGE.png»);
This covers the basics, but let us walk through a few more examples – Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
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
- imagecreate() Creates an empty transparent image.
- A bunch of “drawing settings”. In particular, we need to predefine the colors with imagecolorallocate() before drawing.
- imagefilledrectangle() Fill the background with a solid rectangle.
- imagestring() Write the text.
- imagepng() Save the image into a file. It is optional to use imagedestroy() to clear the image, but good to do so anyway.
EXAMPLE 2) VERTICAL TEXT & OUTPUT TO SCREEN
This is pretty much the same as the above example, but with 2 differences:
- (D) We are using imagestringup() to write the text in a vertical manner now.
- (E) 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
To specify the font, use imagettftext() instead – Please make sure that PHP has read access to the specified font file, or this will draw “nothing”.
P.S. If you want to draw “vertical text” with imagettftext() , just specify a 90 degrees angle (or 270 degrees).
EXAMPLE 4) CENTERING TEXT ON IMAGE
Sadly, 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) .
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s it for the simple script, and here are some small extras and links that may be useful to you.
WRITING MULTIPLE LINES?
There is no straightforward way, the only possibility is to use multiple imagestring() and/or imagettftext() to write multiple lines. As you can guess, this will involve a lot of “X/Y coordinates calculation”. I will not touch on that in this simple guide, follow up with my other “write multi-line” tutorial, link below.
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
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEATSHEET
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!
How to Convert Text to Image using PHP
Most of the image based operations can be performed by using PHP built-in functions. The image-based PHP functions are in GD library and we can use them for converting text into an image.
Before that, we must ensure that the GD library is enabled in the php.ini configuration. You can also run the PHP function phpinfo() to check if the GD is enabled.
I submit a text input via a HTML form to the PHP code. In PHP, I invoke GD library functions to convert this text input into an image.
I create image layers for putting the text and a background. Then, I merged the layers and copy the required portion to show the final output image to the browser. If no text is entered, then it will be resolved with the JavaScript validation.
This screenshot shows the final output after converting the text input to an image. This example may be useful for creating custom captcha using PHP.
Get and Validate Text Input via HTML Form
This code shows the HTML form to get the text input from the user. On submitting this form, the text input will be validated using JavaScript and sent to the PHP. After processing image conversion, the output image will be displayed below this form
Converting Text to an Image using PHP GD functions
In PHP, with the use of GD library function, we can convert text input to an image. I created a transparent image layer to place the text input onto it.
Then I created a background image layer and merge it together with the text input layer using imagecopymerge() . After merging, I slice the required part of the merged layer by using imagecopy() and output the final image to the browser.
Convert Text to Image in PHP
In many cases, we need to create a dynamic image on the fly and write text on the image in our web application. If you have a requirement like this, don’t worry we’ll provide a simple PHP script to convert text to image and save it as PNG or JPG format.
In this tutorial, we are going to show you the easiest way to create an image from text using PHP. To control the text to image creation process, a PHP class will be created. By using this PHP class you can easily create an image and add multiple line text string to the image.
GD library will be used to create and manipulate image file in our PHP script. So before you get started, make sure PHP GD is installed on your server.
Are you want to get the step-by-step guide to installing PHP GD library on the server? Go through the following tutorial links.
TextToImage Class
The TextToImage PHP class helps to generate an image and add text to image. TextToImage class contains 4 functions and the functions will do following.
- createImage() – Creates image from text. The text string needs to be provided that want to write on the image. Also, you can specify the text font size, image width, and image height.
- showImage() – Returns an image that created by the createImage() function.
- saveAsPng() – Save image file as .png format. You can specify the filename and the location to save the image.
- saveAsJpg() – Save image file as .jpg format. You can specify the filename and the location to save the image.
/**
* TextToImage class
* This class converts text to image
*
* @author CodexWorld Dev Team
* @link http://www.codexworld.com
* @license http://www.codexworld.com/license/
*/
class TextToImage private $img;
/**
* Create image from text
* @param string text to convert into image
* @param int font size of text
* @param int width of the image
* @param int height of the image
*/
function createImage($text, $fontSize = 20, $imgWidth = 400, $imgHeight = 80)
//text font path
$font = 'fonts/the_unseen.ttf';
//create the image
$this->img = imagecreatetruecolor($imgWidth, $imgHeight);
//create some colors
$white = imagecolorallocate($this->img, 255, 255, 255);
$grey = imagecolorallocate($this->img, 128, 128, 128);
$black = imagecolorallocate($this->img, 0, 0, 0);
imagefilledrectangle($this->img, 0, 0, $imgWidth - 1, $imgHeight - 1, $white);
//break lines
$splitText = explode ( "\\n" , $text );
$lines = count($splitText);
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->img) - $textWidth)/2;
$y = ((imagesy($this->img) + $textHeight)/2)-($lines-2)*$textHeight;
$lines = $lines-1;
//add some shadow to the text
imagettftext($this->img, $fontSize, $angle, $x, $y, $grey, $font, $txt);
//add the text
imagettftext($this->img, $fontSize, $angle, $x, $y, $black, $font, $txt);
> return true;
>
/**
* Display image
*/
function showImage() header('Content-Type: image/png');
return imagepng($this->img);
>
/**
* 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->img, $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->img, $fileName);
>
>
Convert Text String to Image in PHP
Include TextToImage.php file (TextToImage class) and create an object. Call the createImage() function and provide the text string. If you want to add multiple lines to the image, add “\n” before the new line.
//include TextToImage class
require_once 'TextToImage.php';
//create img object
$img = new TextToImage;
//create image from text
$text = 'Welcome to CodexWorld.\nThe World of Programming.';
$img->createImage($text);
To display image use showImage() function.
//display image
$img->showImage();
To save the image file as PNG or JPG format use saveAsPng() or saveAsJpg() function. Specify the file name and location to save the image, otherwise, the image will be saved with the default name to the same directory where the script is located.
//save image as png format
$img->saveAsPng('codex-text-to-image','images/');
//save image as jpg format
$img->saveAsJpg('codex-text-to-image','images/');
Conclusion
In TextToImage class we’ve used THE UNSEEN font as the text font. If you wish to change the text font, place the font file in the fonts/ directory and specify the font path in createImage() function ( $font ) of TextToImage class.
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question