imagecreate() function in PHP

The imagecreate() function is used to create a new palette−based image resource in PHP. While functional, it's recommended to use imagecreatetruecolor() instead for better image quality, as it creates true color images that support millions of colors rather than the 256−color palette limitation of imagecreate().

Syntax

imagecreate($width, $height)

Parameters

Parameter Type Description
$width int The width of the image in pixels
$height int The height of the image in pixels

Return Value

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

Example

The following example creates a palette−based image with colored text ?

<?php
    // Create a 500x300 palette-based image
    $img = imagecreate(500, 300);
    
    // Allocate colors (first color becomes background)
    $bgcolor = imagecolorallocate($img, 150, 200, 180);
    $fontcolor = imagecolorallocate($img, 120, 60, 200);
    
    // Add text strings with different built-in fonts
    imagestring($img, 5, 150, 120, "Demo Text1", $fontcolor);
    imagestring($img, 4, 150, 100, "Demo Text2", $fontcolor);
    imagestring($img, 3, 150, 80, "Demo Text3", $fontcolor);
    imagestring($img, 2, 150, 60, "Demo Text4", $fontcolor);
    
    // Output as PNG image
    header("Content-Type: image/png");
    imagepng($img);
    
    // Clean up memory
    imagedestroy($img);
?>

Key Points

  • Palette Limitation: imagecreate() creates palette−based images limited to 256 colors
  • First Color: The first color allocated with imagecolorallocate() becomes the background color
  • Better Alternative: Use imagecreatetruecolor() for true color images with better quality
  • Memory Management: Always call imagedestroy() to free memory when done

Conclusion

While imagecreate() works for basic image creation, imagecreatetruecolor() is preferred for modern applications due to its superior color support and image quality capabilities.

Updated on: 2026-03-15T07:48:46+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements