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
-
Economics & Finance
imagecolorexact() function in PHP
The imagecolorexact() function in PHP retrieves the index of a specified color from an image's color palette. This function is useful when working with palette-based images where you need to find the exact index of a specific RGB color combination.
Syntax
imagecolorexact($img, $red, $green, $blue)
Parameters
img − Image resource created with functions like
imagecreatefrompng()orimagecreatefromjpeg()red − Red color component (0-255)
green − Green color component (0-255)
blue − Blue color component (0-255)
Return Value
Returns the color index of the specified RGB color in the image palette, or -1 if the exact color does not exist in the palette.
Example
The following example demonstrates finding color indexes in an image ?
<?php
// Create image resource from PNG file
$img = imagecreatefrompng('/assets/videos/courses/67/images/course_67_image.png');
$colors = Array();
// Get exact color indexes for specific RGB values
$colors[] = imagecolorexact($img, 30, 90, 50);
$colors[] = imagecolorexact($img, 80, 120, 100);
$colors[] = imagecolorexact($img, 25, 80, 50);
$colors[] = imagecolorexact($img, 255, 255, 255); // White
print_r($colors);
// Clean up memory
imagedestroy($img);
?>
The output shows the color indexes found in the image palette ?
Array ( [0] => 1989170 [1] => 5273700 [2] => 1658930 [3] => -1 )
Key Points
The function only works with palette-based images (GIF, PNG with palette)
Returns
-1if the exact RGB combination doesn't exist in the paletteUse
imagecolorallocate()to add colors if they don't existRGB values must be between 0 and 255
Conclusion
The imagecolorexact() function is essential for working with palette-based images when you need to find specific color indexes. Use it to verify color existence before performing pixel operations.
