Creating an Image from Text with PHP and GD Library

In this tutorial, we will tackle about Generating an Image from String or Text using PHP and GD Library. This tutorial aims to provide the students and new in PHP programming language with a reference for learning that focuses on manipulating images using the said library and programming language. Here, I will explain the usage of the useful functions that will be use in a sample web application script that consist of converting the provided text into an image.

What is GD Library?

The `GD Library`, short for "Graphic Draw Library", is a widely used library in PHP for image creation and manipulation. This library is equipped with functions and capabilities primarily tailored for dynamic image generation and editing tasks, including creating thumbnails, adding text to images, drawing shapes, and performing image transformations like resizing and cropping.

Explore some of the small PHP projects that I've personally created and published on this website, all utilizing the GD Library:

Developing a Basic PHP Web Application

Let's now embark on creating a straightforward web application using the PHP programming language. This application's primary functionality is to transform a string into an image. It has the ability to generate an image with the provided string placed in two different orientations: Horizontal and Vertical.

Prior to getting started, please ensure that you have downloaded and installed the following on your local machine if they are not already in place:

  • XAMPP/WAMP web server or an equivalent
  • Code Editor such as MS Visual Studio Code, Sublime Text, or Notepad++

Enabling the GD Library

Once you have successfully installed the required software, you can proceed to enable the GD Library. To do this, locate the `php.ini` file in the designated path of your chosen web server, for example, (C:\xampp\php\php.ini). Next, open the file using your installed code editor and navigate to the line containing `;extension=gd`. Remove the semicolon at the beginning of this line, save the file, and then run or start your Apache or related web server service on your local machine. Ensure that you restart the service if it's already running.

Creating an Image from Text with PHP and GD Library

Designing the User Interface for the Web Application

Now, let's proceed with the creation of the HTML file that will contain the necessary elements for our web page's user interface. This web page boasts a simple design using the Bootstrap Framework and features a form with fields for entering text and selecting the desired string placement. To get started, open your code editor, create a new HTML file, and save it as `index.html`. You can refer to the following script to structure the HTML file for your web application.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <title>String to Image Conversion</title>
  6. <!-- Bootstrap 5.3 CSS-->
  7. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  8. <!-- jQuery -->
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  10. <!-- Bootstrap 5.3 JS-->
  11. <script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  12. </head>
  13. <nav class="navbar navbar-expand-lg bg-body-tertiary">
  14. <div class="container-fluid">
  15. <a class="navbar-brand" href="#">Generate Image From String</a>
  16. </div>
  17. </nav>
  18. <div class="container-md py-4">
  19. <div class="card rounded-0">
  20. <div class="card-header rounded-0">
  21. <div class="card-title">Generate Image:</div>
  22. </div>
  23. <div class="card-body rounded-0">
  24. <form action="generate_image.php" id="string-to-img-frm" target="_blank" method="POST">
  25. <div class="container-fluid">
  26. <div class="mb-3">
  27. <label for="string" class="form-label">Enter String to Convert</label>
  28. <textarea name="string" id="string" cols="30" rows="10" class="form-control rounded-0" colspan="4">Welcome to Sourcecodester! www.sourcecodester.com</textarea>
  29. </div>
  30. <div class="mb-3">
  31. <label for="placement" class="form-label">String Placement</label>
  32. <select name="placement" id="placement" cols="30" rows="10" class="form-control rounded-0">
  33. <option value="0">Horizontally</option>
  34. <option value="90">Vertically</option>
  35. </select>
  36. </div>
  37. </div>
  38. </form>
  39. </div>
  40. <div class="card-footer">
  41. <div class="d-flex w-100 justify-content-center">
  42. <button class="btn btn-primary rounded-pill" type="submit" form="string-to-img-frm">Generate Image</button>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47.  
  48. </body>
  49. </html>

Developing the Main Script

Now, it's time to create the PHP script responsible for generating an image that incorporates the text entered in the form. Begin by crafting a new PHP file and saving it as `generate_image.php`. This file encompasses the procedures that utilize the functions and capabilities of the GD Library to achieve the objective of our sample application. You can refer to the PHP script provided below for guidance:

  1. <?php
  2. header("Content-type: image/png");
  3. extract($_POST);
  4. // Canvas Size
  5. $imageHeight = 400;
  6. $imageWidth = 400;
  7.  
  8. // creating the image canvas
  9. $image = imagecreatetruecolor($imageWidth, $imageHeight);
  10.  
  11. /**
  12.   * Setting up the String Colors
  13.   */
  14. $lightBlue = imagecolorallocate($image, 22, 72, 99);
  15. $white = imagecolorallocate($image, 255, 255, 255);
  16.  
  17. /**
  18.   * Setting up font size
  19.   */
  20. $fontSize = 13.5;
  21. $fontWidth = imagefontwidth($fontSize);
  22. $fontHeight = $fontSize / 2;
  23.  
  24. $fontFile = realpath(__DIR__ . "\PentaGrams-Malefissent.ttf");
  25. $fontAngle = $placement;
  26.  
  27. // Setting Image Bacground
  28. imagefill($image, 0, 0, $lightBlue);
  29. $text = wordwrap($string, floor(400 / $fontSize), PHP_EOL, false);
  30. $lines = explode(PHP_EOL, $text);
  31. $height_offset = 0;
  32.  
  33.  
  34. foreach($lines as $line){
  35. $line = trim($line);
  36.  
  37. // Line width
  38. $width_of_line = $fontWidth * strlen( $line );
  39.  
  40. if($placement == 0){
  41. // X Position of the string in image canvas
  42. $stringX = ( $imageWidth - $width_of_line ) / 2;
  43. // Y Position of the string in image canvas
  44. $stringY = ( ( $imageHeight - ( $fontHeight * count( $lines ) ) ) / 2 ) + ($height_offset * 2.5) ;
  45. }else{
  46. // X Position of the string in image canvas
  47. $stringX = ( ( $imageWidth - ( $fontWidth * count( $lines ) ) ) / 2 ) + ($height_offset * 2.5) ;
  48. // Y Position of the string in image canvas
  49. $stringY = $imageHeight - (( $imageHeight - $width_of_line ) / 2);
  50. }
  51.  
  52. // Height offset
  53. $height_offset += $fontHeight;
  54.  
  55. // Rendering String to Image
  56. imagettftext($image, $fontSize, $fontAngle, $stringX, $stringY, $white, $fontFile, $line);
  57. }
  58. // Render Image
  59. imagepng($image);
  60. // Destroy Image
  61. imagedestroy($image);
  62.  
  63. ?>

Below, you'll find a list of essential functions from the GD Library that I've employed in the provided PHP script for generating an image from the text entered in the form:

  • `imagecreatetruecolor(int $width, int $height)` - This function creates a new true color image that serves as the canvas for the image.
  • `imagecolorallocate(GdImage $image, int $red, int $green, int $blue)` - This function allocates a color for an image using RGB color codes.
  • `imagettftext(GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font_filename, string $text, array $options = [])` - This function writes text to the image using TrueType Fonts. For this script, you can download any desired TTF font file and specify the file path in the `$fontFile` variable.
  • `imagepng(GDImage $image, $file = null, int $quality = -1, int $filters = -1)` - This function is designed to output a PNG image to either the browser or a file.

For further details about these functions and additional functions provided by the GD Library, you can visit the PHP manual at (https://www.php.net/manual/en/ref.image.php).

Visual Results of the Web Application

Here, you can view snapshots that illustrate the outcomes produced by the script I've shared previously.

Page UI

Creating an Image from Text with PHP and GD Library

Generated Image using Horizontal Placement

Creating an Image from Text with PHP and GD Library

Generated Image using Vertical Placement

Creating an Image from Text with PHP and GD Library

That's it! I've also made the source code available for download as a compressed file right below this article. Simply click the download button to access it.

I hope that this tutorial on "Creating an Image from Text with PHP and GD Library" has provided you with the knowledge and tools you were seeking, and that you'll find it valuable for both your current and future PHP projects. Feel free to explore our website for more Free Source Codes, Tutorials, and Articles that cover a wide range of programming languages.

Happy Coding =)

Add new comment