doulian8554 2012-09-04 07:38
浏览 14
已采纳

PHP色彩强度检测

How can I detect intensity of this hex color: #000000? I can use that method for this code. For example if background color is black, text-color must be set to #FFFFFF (white). I'm using this snippet for generating random color:

$random_color = '#'.base_convert(rand(0, 16777215), 10, 16);
  • 写回答

2条回答 默认 最新

  • duanmei9980 2012-09-04 08:21
    关注

    There're couple of valid approaches but the simpliest is to convert your color to grayscale and then check if result value is in upper half or lower. If in upper, then it's light color and you should use i.e. black as text color, if in lower, then it's dark, so white will work best. Something like this:

    function getReadableTextColor( $backgroundColor ) {
        $R = ($backgroundColor >> 16 ) & 0x000000ff;
        $G = ($backgroundColor >>  8 ) & 0x000000ff;
        $B = ($backgroundColor       ) & 0x000000ff;
    
        // grayscale: 0.3RED + 0.59GREEN + 0.11Blue
        $K = (($R * 0.3) + ($G * 0.59) + ($B * 0.11));
    
        // black fg color for light background, white for dark ones
        return ( $K > 128 ) ? 0x000000 : 0xffffff;
    }    
    

    then use like this

    $bgColor = rand(0, 16777215);
    $bgcolorHTML = '#' . base_convert($bgColor, 10, 16);
    $fgColor = getReadableTextColor( $bgColor );
    $fgColorHtml = '#' . base_convert($fgColor, 10, 16);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大