I want to get brighter hex colour shade output from a given hex value with PHP. For example, I give the colour #cc6699 as input, and I want #ee88aa as the output colour. How would I go about doing this in PHP?
3 Answers
You need to convert the color to RGB, make the additions, and convert back:
// Convert string to 3 decimal values (0-255)
$rgb = array_map('hexdec', str_split("cc6699", 2));
// Modify color
$rgb[0] += 34;
$rgb[1] += 34;
$rgb[2] += 17;
// Convert back
$result = implode('', array_map('dechex', $rgb));
echo $result;
-
@Jon Thanks very much your solution is well and i will do this– AnjumCommented Mar 20, 2011 at 11:06
-
@Jon Jon 1 thing i can not understand in third value difference $rgb[2] += 17; please clear me– AnjumCommented Mar 20, 2011 at 11:10
-
@jon Jon my input value is with # from my database and i need output value also with # hash for using in my css and i can not like to change values from database and my structure there is 32+ values saved with colorpicker.js– AnjumCommented Mar 20, 2011 at 11:16
-
@Anjum:
34 == 0x22and17 = 0x11.0xcc + 0x22=>0xcc,0x66 + 0x22=>0x88,0x99c + 0x11=>0xaa. All together:#cc6699 => #ee88aa.– JonCommented Mar 20, 2011 at 11:17 -
- split the color in three elements: cc, 66, 99
- Convert it to decimal with http://php.net/manual/de/function.hexdec.php
- Increment three decimal values
- Convert decimal to hex again
- put the three elements together
The best solution is to convert the RGB to HSL or HSV (just search google for php converter hsl/hsv).
Then you can play with the 'lightness' or 'value' values of the colorspace.
Afterwards convert it back to RGB colorspace.