In PHP, I am trying to calculate the average color (in hex) between to different hex colors. However, I also need to be able to supply an index number between 0.0 and 1.0.
So for example:
I have
$color1 = "#ffffff"
$color2 = "#0066CC"
If I would write a function to get the average color and I would supply 0.0 as the index number, the function would need to return "#ffffff
". If I would supply 1.0 as the index number, the function would need to return "#0066CC
". However if I would supply 0.2, the function would need to return an average color between the two colors, but still closer to $color1
than to $color2
. If I would supply index number 0.5, I would get the exact average color of both colors.
I have been trying to accomplish this for several days now but I can't seem to figure it out! Any help would therefor be greatly appreciated!
I am not sure if it will compile but if you want the math behind this it would go something like this:
For simplicity, always have $color1
be bigger than $color2
.
$dec1 = hexdec($hex_color1);
$dec2 = hexdec($hex_color2);
$dec1 = ($dec1 < $dec2) ? $dec1^=$dec2^=$dec1^=$dec2 : $dec1;
$new_hex_color = dechex($dec1 - ($dec1 - $dec2)*index_number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With