1

I am using the following function to generate pastel colors. But sometimes it generates dark shades (like #B69C97). How do I ensure that only light shades are generated?

function get_color($name) {
    $hash = md5($name);

    $color1 = hexdec(substr($hash, 8, 2));
    $color2 = hexdec(substr($hash, 4, 2));
    $color3 = hexdec(substr($hash, 0, 2));
    if($color1 < 128) $color1 += 128;
    if($color2 < 128) $color2 += 128;
    if($color3 < 128) $color3 += 128;

    return "#" . dechex($color1) . dechex($color2) . dechex($color3);
}
softwarematter
  • 28,015
  • 64
  • 169
  • 263

2 Answers2

0

#B69C97 is (182,156,151) in RGB. Your definition of "dark" according to your code is less than 128, which is proved to be wrong, since (182, 156, 151) is still "dark" for you. I would try to change this default "dark" value from 128 to something higher, say 160. Just with this example you will eliminate the colors that contain values less than 160, as in your case, and lighten the average output.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
0

Fair few years late, but this might help someone,

    $baseColors = [
        1 => 'r',
        2 => 'g',
        3 => 'b'
    ];
    $colorMap = [];
    $minValue = 155;
    $maxValue = 200;

    $primaryColorIndex = rand(1, 3);

    $primaryColor = $baseColors[$primaryColorIndex];
    unset($baseColors[$primaryColorIndex]);

    $colorMap[$primaryColor] = 255;

    foreach($baseColors as $baseColor) {
        $colorMap[$baseColor] = rand($minValue, $maxValue);
    }

    krsort($colorMap);

    $color = '';
    foreach($colorMap as $value) {
        $color .= $value;
        if($value !== end($colorMap)) {
            $color .= ',';
        }
    }

    return 'rgb(' . $color . ')';

This will return rgb value.

This should generate a random pastel colour which uses red, green or blue as its 'primary' most outspoken colour.

Edit:

    $baseColors = [
        1 => 'r',
        2 => 'g',
        3 => 'b'
    ];
    $colorMap = [];
    $minValue = 155;
    $maxValue = 200;

    $primaryColorIndex = rand(1, 3);

    $primaryColor = $baseColors[$primaryColorIndex];
    unset($baseColors[$primaryColorIndex]);

    $colorMap[$primaryColor] = 255;

    foreach($baseColors as $baseColor) {
        $colorMap[$baseColor] = rand($minValue, $maxValue);
    }

    krsort($colorMap);

    $rgbColor = [];
    foreach($colorMap as $key => $value) {
        $rgbColor[$key] = $value;
    }

    $color = sprintf('#%02x%02x%02x', $rgbColor['r'], $rgbColor['g'], $rgbColor['b']);

This will return a hex value.

Ballard
  • 869
  • 11
  • 25
  • p.s if you need to convert the rgb value to hex, you can follow this answer. https://stackoverflow.com/questions/32962624/convert-rgb-to-hex-color-values-in-php – Ballard Sep 01 '19 at 23:16