PHP imagecolorallocate(): Allocate a Color for an Image

The PHP function imagecolorallocate() assigns a color to an image resource by specifying red, green, and blue components (0‑255 or hexadecimal), returns a color identifier or -1 on failure, and is demonstrated with example code showing how to set background, white, and black colors.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP imagecolorallocate(): Allocate a Color for an Image

The imagecolorallocate() function in PHP creates a color identifier for a given image resource by combining red, green, and blue components. The RGB values can be supplied as integers ranging from 0 to 255 or as hexadecimal values (0x00‑0xFF).

Parameters: resource $image – the image resource to which the color will be applied; int $red, int $green, int $blue – the intensity of each color channel.

Return value: On success, the function returns an integer identifier representing the allocated color. If the allocation fails, it returns -1.

Example usage:

<?php
$im = imagecreate('example.jpg', 100, 100);
// Set background to red
$background = imagecolorallocate($im, 255, 0, 0);
// Define additional colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Using hexadecimal notation
$whiteHex = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$blackHex = imagecolorallocate($im, 0x00, 0x00, 0x00);
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendGraphicsImagecolor
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.