Home > Blockchain >  How to convert 8-digit hex to the equivalent 6-digit hex code in php?
How to convert 8-digit hex to the equivalent 6-digit hex code in php?

Time:08-27

I am trying to determine colors for my site's themes. A great way I've found to do so is to take a main 6-digit hex color and simply add opacity on to the end of the hex code to get a complimentary color. The problem I'm having is that any time the secondary (the 8-digit hex code) color is to be on top of the main color you can't see it. Is there any way in css or php to convert an 8-digit hex code to it's equivalent color in a normal 6-digit hex code.

For example, my main color and secondary colors are as follows:

#053d06
#053d0614

I could go into a color picker and grab the secondary color and manually code it that way, but I'm trying to do it programmatically. I have tried clemblanco's rgba2hex/hex2rgba code, but that seems to just translate it back to the main color instead of the equivalent secondary color. Any help is appreciated! Thank you.

ETA: More directly I want a hex color that is the same color as the 8-digit code put over a white background. Thank you.

CodePudding user response:

Directly getting the substring or dividing off the two hex digits 16**2 -> 256 could be a practical way to truncate 'em if that's all you're after

php > $hex = "#053d0614";
php > echo substr($hex, 0, 7);
#053d06
php > echo '#'.substr('000000'.dechex(intdiv(hexdec($hex), 256)), -6);
#053d06

CodePudding user response:

SOLUTION: I ended up just adjusting the brightness of my main color instead of trying to convert an alpha hex to a non-alpha hex. Here is what I am using and it works great:

function adjustBrightness($hexCode, $adjustPercent) {
    $hexCode = ltrim($hexCode, '#');

    if (strlen($hexCode) == 3) {
        $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
    }

    $hexCode = array_map('hexdec', str_split($hexCode, 2));

    foreach ($hexCode as & $color) {
        $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
        $adjustAmount = ceil($adjustableLimit * $adjustPercent);

        $color = str_pad(dechex($color   $adjustAmount), 2, '0', STR_PAD_LEFT);
    }

    return '#' . implode($hexCode);
}
  • Related