How to create a new true-color image in PHP using imagecreatetruecolor()?

The imagecreatetruecolor() function is an inbuilt function in PHP that creates a new true-color image resource. It returns a blank image canvas of the specified dimensions that can be used for drawing operations.

Syntax

resource imagecreatetruecolor($width, $height)

Parameters

The imagecreatetruecolor() function takes two parameters:

  • $width − The width of the image in pixels.

  • $height − The height of the image in pixels.

Return Value

Returns an image resource identifier on success, or FALSE on errors.

Example 1 − Creating a Polygon Image

This example creates a true-color image and draws a triangle polygon on it:

<?php
    // Set the vertices of polygon
    $values = array(
        150, 50,  // Point 1 (x, y)
        50, 250,  // Point 2 (x, y)
        250, 250  // Point 3 (x, y)
    );
    
    // Create the size of image or blank image
    $image = imagecreatetruecolor(700, 350);

    // Set the background color of image
    $background_color = imagecolorallocate($image, 122, 122, 122);

    // Fill background with above selected color
    imagefill($image, 0, 0, $background_color);

    // Allocate a color for the polygon
    $image_color = imagecolorallocate($image, 0, 255, 255);

    // Draw the polygon
    imagepolygon($image, $values, 3, $image_color);

    // Output the picture to the browser
    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);
?>

Example 2 − Creating Text Image

This example creates a GD image stream with text:

<?php
    header('Content-Type: image/png');
    $img = @imagecreatetruecolor(550, 220)
        or die('Cannot Initialize new GD image stream');
    
    $text_color = imagecolorallocate($img, 255, 255, 0);
    
    imagestring($img, 10, 50, 50, 'A Simple PHP Example', $text_color);
    imagepng($img);
    imagedestroy($img);
?>

Note: These examples require the GD extension and should be run in a web server environment to generate image output properly.

Key Points

  • Always use imagedestroy() to free up memory after creating images

  • Set appropriate headers before outputting images to browser

  • The function creates a black canvas by default

  • Use imagecolorallocate() to define colors for the image

Conclusion

The imagecreatetruecolor() function is essential for creating dynamic images in PHP. It provides a foundation for drawing shapes, adding text, and generating various visual content programmatically.

Updated on: 2026-03-15T09:45:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements