How to Convert Text to Image using PHP

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

Get and Validate Text Input via HTML 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()));

Leave a Reply