How to Convert Text to Image using PHP

by Vincy. Last modified on July 8th, 2022.

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.

php-text-to-image-conversion-output

 

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">

        <div>
            <label>Enter Text:</label> <input type="text"
                class="input-field" name="txt_input" maxlength="50">
        </div>
    </div>
    <div class="button-row">
        <input type="submit" id="submit" name="submit"
            value="Convert">
    </div>
</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.

<?php
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);
        ob_start();
        imagepng($img);
        printf('<img src="data:image/png;base64,%s"/ width="100">', base64_encode(ob_get_clean()));
    }
}
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

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

  • Daniel Martins says:

    Unfortunately it does not work with accented characters so Latin America and Europe are out.

    • Vincy says:

      Hi Daniel,

      The following code snippet writes special characters and you may try it:

      header(“Content-type: image/jpeg”);
      $imgPath = ‘http://upload.wikimedia.org/wikipedia/en/3/37/VII-200-bakside.jpg’;
      $image = imagecreatefromjpeg($imgPath);
      $color = imagecolorallocate($image, 0,0, 250);
      $string = “A&B UK LIMITED”;
      $fontSize = 5;
      $x = 50;
      $y = 50;
      imagestring($image, $fontSize, $x, $y, $string, $color);
      imagejpeg($image,’test.jpeg’,75);
      imagejpeg($image);

  • Sunita says:

    I add a gif image with custom Text, but it’s not working.I want to create a gif image. please help Me.

    • Vincy says:

      Hi Sunita,

      The PHP core functions that I have used do not support GIF image creation. You may try with imagegif() function.

  • Gaurav says:

    If we want convert a large text or a passage type text into image, so what should we change in script and make sure the image will be without background colour.

  • Trov Aziende says:

    Thank you, I used this on my website to protect email from spam bots! This was very helpful!

  • shradha says:

    how to get larger text like 4000 words in that text to image

  • Christopher Bourne says:

    This is really good, can you change the font style on this?

  • Noah says:

    It is possible to Concert HTML Content to img?

  • AKR says:

    Hi, can you tell mw how I should save this text as an image file to use it as a watermark?

  • Muhammad Erfan says:

    Thank you very much…

  • hanuman says:

    thanks.. very help full

  • Rahul says:

    Thanks Vincy Exactly what i was looking :)

  • Devraj Shrestha says:

    How we can do this if we give fixed width and we have multiple numbers of lines.

    • Vincy says:

      Hi Devraj,

      From Gannon’s reply on php.net manual,

      function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
      if (strlen($color) != 6) $color = 000000;
      $int = hexdec($color);
      $h = imagefontheight($font);
      $fw = imagefontwidth($font);
      $txt = explode(“\n”, wordwrap($txt, ($w / $fw), “\n”));
      $lines = count($txt);
      $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
      $bg = imagecolorallocate($im, 255, 255, 255);
      $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
      $y = 0;
      foreach ($txt as $text) {
      $x = (($w – ($fw * strlen($text))) / 2);
      imagestring($im, $font, $x, $y, $text, $color);
      $y += ($h + $space);
      }
      header(‘Content-type: image/jpeg’);
      die(imagejpeg($im));
      }

      You can take clue from the above snippet and apply here.

  • Johnson says:

    Can this library support Chinese text?

    Thanks

  • Oliver says:

    Wonderful, Vincy.
    Your solution is easily transposable on every project.
    It’s very useful to protect from spam bots with a minimal adaptation.

    Thank you very much.

  • Waleed Barakat says:

    First: thanks for the quick tutorial. Second: where the image saved?

    • Vincy says:

      Hi Waleed,

      The raw image stream will be output directly and written based on src=”data:image/png;… this code.

Leave a Reply

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

↑ Back to Top

Share this page