4

I have this Javascript function to get the right color (white or black) for text depending on the given HEX color of the background, which works well:

// Ideal color
function getRGBComponents(color) {
    var r = color.substring(1, 3),
        g = color.substring(3, 5),
        b = color.substring(5, 7);
    return {
        R: parseInt(r, 16),
        G: parseInt(g, 16),
        B: parseInt(b, 16)
    };
}
function idealTextColor(bgColor) {
    if (bgColor.length === 4) {
        bgColor = '#' + bgColor[1] + bgColor[1] + bgColor[2] + bgColor[2] + bgColor[3] + bgColor;
    }
    var nThreshold = 105,
        components = getRGBComponents(bgColor),
        bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);
    return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";
}

idealTextColor("#123123");

I've converted it to PHP:

// Ideal color
function getRGBComponents($color) {
    $r = substr($color, 1, 3);
    $g = substr($color, 3, 5);
    $b = substr($color, 5, 7);
    return Array(
        "R" => intval($r, 16),
            "G" => intval($g, 16),
            "B" => intval($b, 16)
        );
}
function idealTextColor($bgColor) {
    if (strlen($bgColor) == 4) {
        $bgColor = '#' . $bgColor[1] . $bgColor[1] . $bgColor[2] . $bgColor[2] . $bgColor[3] . $bgColor[3];
    }
    $nThreshold = 105;
    $components = getRGBComponents($bgColor);
    $bgDelta = ($components["R"] * 0.299) + ($components["G"] * 0.587) + ($components["B"] * 0.114);

    if((255 - $bgDelta) < $nThreshold) {
        return "#000000";
    } else {
        return "#FFFFFF";
    }
}

idealTextColor("#123123");

And it doesn't work, it gives me always #00000 as color (FIDDLE). How can I fix it to works again? Or maybe someone has a better function to perform the same task?

4

1 回答 1

3
$r = substr($color, 1, 2);
$g = substr($color, 3, 2);
$b = substr($color, 5, 2);

substr 的第二个参数是长度,而不是结束索引。

于 2013-09-13T19:46:05.057 回答