0

我正在尝试创建一个生成两种颜色的小脚本,如果一种用作背景,另一种用作字体颜色,则将根据以下准则可读:

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

W3C 的 Web 可访问性指南(并且不充分)

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

(这是一个建议的算法,仍然可以更改。)

如果两种颜色之间的亮度差异和色差大于设定范围,则两种颜色提供良好的颜色可视性。

颜色亮度由以下公式确定:((红色值 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 所允许的时间......关于如何优化它的建议?:)

4

1 回答 1

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% 的执行时间。

于 2013-04-28T17:13:04.287 回答