How to Convert Text to Image using PHP

by Vincy. Last modified on May 23rd, 2021.

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.

View Demo

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

<form name="form" id="form" method="post" action="index.php"
        enctype="multipart/form-data" onsubmit="return validateForm();">
    <div class="form-row">

            <label>Enter Text:</label> <input type="text"
                class="input-field" name="txt_input" maxlength="50">
    <div class="button-row">
        <input type="submit" id="submit" name="submit"

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.

if (isset($_POST['submit'])) {
    $img = imagecreate(500, 100);
    $textbgcolor = imagecolorallocate($img, 173, 230, 181);
    $textcolor = imagecolorallocate($img, 0, 192, 255);
    if ($_POST['txt_input'] != '') {
        $txt = $_POST['txt_input'];
        imagestring($img, 5, 5, 5, $txt, $textcolor);
        printf('<img src="data:image/png;base64,%s"/ width="100">', base64_encode(ob_get_clean()));

View DemoDownload

Comments to “How to Convert Text to Image using PHP”

Leave a Reply

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

↑ Back to Top