Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the average color between two colors in PHP, using an index number as reference value

Tags:

php

hex

colors

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!

like image 849
R_K Avatar asked Dec 24 '10 11:12

R_K


1 Answers

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)
like image 95
Vuk Avatar answered Sep 22 '22 11:09

Vuk