Convert Text To Image Using PHP

Convert Text To Image Using PHP

Here we show how you can convert text to image help of PHP built-in functions. First we need to check  GD library extension  in our current PHP version. If not enable go to the  php.ini configuration file and enable GD library .

We submit a text input via a HTML form to the PHP code. In PHP, We invoke GD library functions to convert this text input into an image.

Get 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 sent to the PHP and after processing image conversion, the output image will be displayed below this form.

				
					<!DOCTYPE html>
<html>
  <head>
    <title>Inflay.com | Convert Text To Image Using PHP</title>
     	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  </head>
  <body>

<h3>Convert Text To Image Using PHP</h3>

      
      <form action="" method="post">
            <label for="country">Enter Text</label>
              <input type = "text" id="txtinput" name="txtinput" value = "">
              <lable id="email_msg"></lable>
              <input type = "submit" name="convert" id="convert" value="Convert">
      </form>
  </body>
</html>
				

Convert Text to Image using PHP GD functions

				
					<?php
  if (isset($_POST['convert'])) 
  {
    if (!empty($_POST['txtinput'])) 
    {
      $input = $_POST['txtinput'];
      $width = (strlen($input)*9)+60;
      $height = 30;
      $textImage = imagecreate($width, $height);
      $color = imagecolorallocate($textImage, 0, 0, 0);
      imagecolortransparent($textImage, $color);
      imagestring($textImage, 5, 10, 5, $input, 0xFFFFFF);
      // Increase text-font size
      imageline($textImage, 30, 45, 165, 45, $color);
      //break lines
      $input_text = explode ( "\n" , $input );
      $lines = count($input_text);
      // create background image layer
      $background = imagecreatefromjpeg('wood.jpg');
      // Merge background image and text image layers
      imagecopymerge($background, $textImage, 15, 15, 0, 0, $width, $height, 100);
      $output = imagecreatetruecolor($width, $height);
      imagecopy($output, $background, 0, 0, 20, 13, $width, $height);
      ob_start();
      imagepng($output);
      printf('<img decoding="async" id="output" src="data:image/png;base64,%s" />', base64_encode(ob_get_clean()));
    }
  }  
?>
				

I hope this article helps you.
Thanks for visiting Inflay.com .