Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
imagecolorset() function in PHP
The imagecolorset() function modifies the color of a specific palette index in palette-based images. This is particularly useful for creating flood-fill-like effects where you want to change all pixels of a particular color to a new color.
Syntax
imagecolorset(resource $image, int $index, int $red, int $green, int $blue [, int $alpha])
Parameters
image − An image resource created by functions like
imagecreate()index − The palette index to modify (0-255)
red − Red component value (0-255)
green − Green component value (0-255)
blue − Blue component value (0-255)
alpha − Transparency level (0-127, where 0 = opaque, 127 = transparent)
Return Value
This function returns NULL on success.
Example
Here's a complete example showing how to use imagecolorset() to modify palette colors ?
<?php
// Create a palette-based image
$img = imagecreate(300, 200);
// Allocate initial colors
$black = imagecolorallocate($img, 0, 0, 0); // Background (index 0)
$red = imagecolorallocate($img, 255, 0, 0); // Red (index 1)
$green = imagecolorallocate($img, 0, 255, 0); // Green (index 2)
// Draw some rectangles with different colors
imagefilledrectangle($img, 50, 50, 100, 100, $red);
imagefilledrectangle($img, 150, 50, 200, 100, $green);
// Change the red color (index 1) to blue
imagecolorset($img, 1, 0, 0, 255);
// Change the green color (index 2) to yellow
imagecolorset($img, 2, 255, 255, 0);
// Output the image
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
?>
Key Points
Works only with palette-based images created with
imagecreate()Does not work with truecolor images created with
imagecreatetruecolor()All pixels using the specified color index will change simultaneously
Alpha parameter is optional and only works with images supporting transparency
Conclusion
The imagecolorset() function provides an efficient way to change colors in palette-based images. It's particularly useful for creating color replacement effects or dynamically modifying image color schemes.
