How to Generate an Image and Add Text Using PHP

Last updated on May 7th, 2025 at 08:04 am

Creating dynamic images with custom text can enhance user engagement on your website. PHP’s GD library provides a straightforward way to generate images and overlay text.

Prerequisites

Before diving in, ensure the following:

  • Write Permissions: The directory where the image will be saved should have appropriate write permissions.
  • GD Library Installed: The GD library must be enabled in your PHP environment.

Step-by-Step Guide

Here’s a simple PHP script that creates a 400×200 red image and writes a blue text message on it:

<?php
function create_image(){
    // Create a 400x200 image
    $im = @imagecreate(400, 200) or die("Cannot initialize new GD image stream");

    // Allocate colors
    $background_color = imagecolorallocate($im, 255, 0, 0); // Red background
    $text_color = imagecolorallocate($im, 0, 0, 255); // Blue text

    // Add text to the image
    imagestring($im, 5, 10, 10, 'Hello from webtutorials.dev', $text_color);

    // Save the image as 'image.png'
    imagepng($im, "image.png");

    // Free up memory
    imagedestroy($im);
}

// Call the function to create the image
create_image();

// Provide a link to view the image
echo "View Image Created: <a href='image.png'>Image</a>";
?>

Explanation of the Code:

  • imagecreate(400, 200): Creates a blank image with a width of 400 pixels and a height of 200 pixels.
  • imagecolorallocate(): Defines colors for the background and text.
  • imagestring(): Writes the specified text onto the image.
  • imagepng(): Saves the image in PNG format.
  • imagedestroy(): Frees up memory associated with the image

Tips and Best Practices

  • Use imagecreatetruecolor(): For better quality images, consider using imagecreatetruecolor() instead of imagecreate().
  • Font Customization: To use custom fonts, explore functions like imagettftext() which allows adding TrueType fonts to images.
  • Error Handling: Always include error handling to manage scenarios where the image creation might fail.

Demo

4 Comments

  1. Mahmudul Islam

    Excellent tutorial, Thank for give the information.

  2. Gandi

    Thank you, this is very helpfully..

  3. Gina

    Good read. Thank you.