Jump to content

crazy hex color question


frijole

Recommended Posts

What would you be multiplying them together for?  I understand why you would want to take the average.

 

As for how to do it, base_convert() will convert a hex string into an integer, after which you can use normal maths on it.  Or are you looking for a method that will operate on actual hex strings themselves?

 

Edit: And for averaging the colours, you would need to split the colour into the red green and blue components before doing the maths (at least that makes it easier).

Link to comment
Share on other sites

You could split them into their red, green and blue components and average those

 

<?php
$col_a = 0xFFFF00;
$col_b = 0xEB9642;

$a = sprintf('#%06X', $col_a);
$b = sprintf('#%06X', $col_b);
$c = sprintf('#%06X', avgColor ($col_a, $col_b));

echo "<span style='background-color: $a'>--$a--</span>";
echo "<span style='background-color: $c'>--average--</span>";
echo "<span style='background-color: $b'>--$b--</span>";

function colorSplit($c)
{
    $red = ($c >> 16) & 0xFF;
    $green = ($c >>  & 0xFF;
    $blue = $c  & 0xFF; 
    return array($red, $green, $blue);
}

function avgColor ($a, $b)
{
    $a = colorSplit($a);
    $b = colorSplit($b);
    
    $r = ($a[0] + $b[0]) / 2;
    $g = ($a[1] + $b[1]) / 2;
    $b = ($a[2] + $b[2]) / 2;
    
    return ($r << 16) + ($g <<  + $b;
}

?>

Link to comment
Share on other sites

  • 2 weeks later...

I believe hex codes are in the form

RRGGBB

 

so if u want to find a "intermediate"

take the avg of the RR avg of GG and avg BB and then use those (as integers not floats)

 

you will of course need to first split it into single digits, then convert from base16 to base 10 numbers (so A = 10 B = 11 C = 12) and then avg and convert back to 16 (14 = E 15 = F)  and then rebuild the new hex.  I don't know if it will be a quote "intermediate", but you can probably tweak it somehow to do what you want.

 

 

Alternatively you can use equations to go from the hex codes to RGB and then probably get a more refined "intermediate"

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.