imagecolorallocate() function in PHP

The imagecolorallocate() function in PHP allocates a color for an image using RGB values. This function is essential for creating colored graphics and backgrounds in image manipulation.

Syntax

int imagecolorallocate($image, $red, $green, $blue)

Parameters

  • $image: Image resource created with imagecreatetruecolor() or imagecreate()

  • $red: Red color component (0-255)

  • $green: Green color component (0-255)

  • $blue: Blue color component (0-255)

Return Value

Returns a color identifier on success, or FALSE on failure. The color identifier can be used with other image functions.

Example

Here's how to create an image with a custom background color −

<?php
    // Create a 600x220 image
    $img = imagecreatetruecolor(600, 220);
    
    // Allocate a dark blue color (RGB: 20, 50, 120)
    $bgcolor = imagecolorallocate($img, 20, 50, 120);
    
    // Fill the entire image with the background color
    imagefill($img, 0, 0, $bgcolor);
    
    // Output as PNG image
    header("Content-type: image/png");
    imagepng($img);
    
    // Clean up memory
    imagedestroy($img);
?>

Creating Multiple Colors

You can allocate multiple colors for complex graphics −

<?php
    $img = imagecreatetruecolor(300, 200);
    
    // Allocate different colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $red = imagecolorallocate($img, 255, 0, 0);
    $green = imagecolorallocate($img, 0, 255, 0);
    $blue = imagecolorallocate($img, 0, 0, 255);
    
    // Use colors for drawing
    imagefill($img, 0, 0, $white);
    imagefilledrectangle($img, 50, 50, 150, 100, $red);
    
    header("Content-type: image/png");
    imagepng($img);
    imagedestroy($img);
?>

Output

The first example produces a solid dark blue image:

600x220 Dark Blue Background

Conclusion

The imagecolorallocate() function is fundamental for image creation in PHP, allowing you to define custom colors using RGB values. Always remember to destroy images with imagedestroy() to free memory.

Updated on: 2026-03-15T08:04:36+05:30

633 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements