2013-04-28 37 views
0

我试图创建一个小的脚本,其产生两种颜色,如果一个作为背景,一个作为字体颜色,将根据以下准则是可读:优化彩色图像生成可读性

http://www.hgrebdes.com/colour/spectrum/colourvisibility.html

Web可访问准则从W3C(和不足)

颜色可见性可以根据下列 算法来确定:

(这是所提出的算法,仍然是开放的改变。)

两种颜色提供良好的颜色可见度,如果亮度差 和两个颜色之间的色差是大于设定 范围更大。 ((红色值X 299)+(绿色值X 587)+(蓝色值X 114))/ 1000注意:这个 算法取自一个公式转换公式RGB值为YIQ 值。该亮度值为 颜色提供了可感知的亮度。 (最大(红色) 值1,红色值2) - 最小值(红色值1,红色值2))+(最大值 (绿色值1,绿色值2) - 最小值(绿色值1,绿色值 2))+(最大(蓝色值1,蓝值2) - 最小(蓝色值1, 蓝值2))

范围为颜色亮度差别是125颜色 的区别是500.

我的代码是:

do { 

    $bg[0] = rand(0, 255); 
    $bg[1] = rand(0, 255); 
    $bg[2] = rand(0, 255); 
    $bg[3] = ($bg[0] + $bg[1] + $bg[2])/1000; 

    $txt[0] = rand(0, 255); 
    $txt[1] = rand(0, 255); 
    $txt[2] = rand(0, 255); 
    $txt[3] = ($txt[0] + $txt[1] + $txt[2])/1000; 

    //Brightness Difference = Brightness of color 1 - Brightness of color 2 
    $brightnessDifference = abs($bg[3] - $txt[3]); 

    //Color difference = Maximum (Red1, Red2) - Minimum (Red1, Red2) etc for Blue and Green 
    $colorDifference = max($bg[0], $txt[0]) - min($bg[0], $txt[0]) + max($bg[1], $txt[1]) - min($bg[1], $txt[1]) + max($bg[2], $txt[2]) - min($bg[2], $txt[2]); 
} while($brightnessDifference < 125 || $colorDifference < 500) 

但是执行时间超过了PHP允许的时间......关于如何优化它的建议? :)

回答

1

您有一个导致无限循环的错误,使您的脚本运行时间超过最大脚本执行时间。

这三行代码中的有车:

$bg[3] = ($bg[0] + $bg[1] + $bg[2])/1000; 
$txt[3] = ($txt[0] + $txt[1] + $txt[2])/1000; 
$brightnessDifference = abs($bg[3] - $txt[3]); 

$brightnessDifference永远不会大于125,所以while()将永远运行。

这里是该溶液中,从你的问题引述:

颜色亮度由下面的公式确定:((红色值X 299)+(绿色值X 587)+(蓝色值X 114) )/ 1000注意:此算法取自将RGB值转换为YIQ值的公式。这个亮度值给出了一种颜色的感知亮度。

你问的优化,虽然你不需要它,一旦你删除了错误,你的代码可以通过改变rand()进行优化:

do { 

    $bg[0] = rand() & 255; 
    $bg[1] = rand() & 255; 
    $bg[2] = rand() & 255; 
    $bg[3] = ($bg[0] + $bg[1] + $bg[2])/1000; 

    $txt[0] = rand() & 255; 
    $txt[1] = rand() & 255; 
    $txt[2] = rand() & 255; 
    $txt[3] = ($txt[0] + $txt[1] + $txt[2])/1000; 

    //Brightness Difference = Brightness of color 1 - Brightness of color 2 
    $brightnessDifference = abs($bg[3] - $txt[3]); 

    //Color difference = Maximum (Red1, Red2) - Minimum (Red1, Red2) etc for Blue and Green 
    $colorDifference = max($bg[0], $txt[0]) - min($bg[0], $txt[0]) + max($bg[1], $txt[1]) - min($bg[1], $txt[1]) + max($bg[2], $txt[2]) - min($bg[2], $txt[2]); 
} while($brightnessDifference < 125 || $colorDifference < 500) 

您节省高达30%的执行时间。