首页 > 解决方案 > 字符串php的深色十六进制颜色

问题描述

我想通过 php 中的字符串名称生成深色的十六进制背景颜色?相同字符串的十六进制颜色必须相同,我尝试使用哈希:

 $backgrounColor = substr(md5('blabla')), 0, 6);
 $fontColor = 'fff';

标签: php

解决方案


假设当您说“深色”时,您的意思是所有通道都处于特定强度下的颜色,您可以执行以下操作:

function hashColor($srcString) {
    $maxItensity = 0x80;

    $hash  = crc32($srcString);
    $red   = ($hash & 0xFF0000) >> 16;
    $green = ($hash & 0x00FF00) >> 8;
    $blue  = ($hash & 0x0000FF);

    $red -= ($red > $maxItensity) ? 0xFF - $maxItensity : 0;
    $green -= ($green > $maxItensity) ? 0xFF - $maxItensity : 0;
    $blue -= ($blue > $maxItensity) ? 0xFF - $maxItensity : 0;

    $color = ($red << 16) + ($green << 8) + ($blue);

    return "#" . str_pad(dechex($color), 6, "0", STR_PAD_LEFT);
}

推荐阅读